调整文件夹中所有图像的大小
本文关键字:图像 文件夹 调整 | 更新日期: 2023-09-27 18:18:18
我正试图将同一文件夹中找到的所有图像调整为相同的大小。这里是我的代码,但它不工作。请提供一点帮助(忽略"CombineImages(files);"这是程序的另一种工作方式)
private void cmdCombine_Click(object sender, EventArgs e)
{
//Change the path to location where your images are stored.
DirectoryInfo directory = new DirectoryInfo(@"C:'Users'Elder Zollinger'Desktop'Images");
if (directory != null)
{
FileInfo[] files = directory.GetFiles();
ResizeImages(files);
CombineImages(files);
}
private void ResizeImages(FileInfo[] files)
{
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
var newImage = ScaleImage(img, 200, 400);
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
您没有保存调整大小的图像。试试这个:
private void ResizeImages(FileInfo[] files)
{
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
var newImage = ScaleImage(img, 200, 400);
img.Dispose();
newImage.Save(file.FullName);
}
}
您需要在覆盖原始图像之前处理它。