我正在尝试将在同一文件夹中找到的所有图像调整为相同大小。这是我的代码,但它不起作用。请稍微帮忙(忽略“CombineImages(文件);”这是该程序正常工作的另一种方法)
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;
}
答案 0 :(得分:0)
您没有保存已调整大小的图像。试试这个:
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);
}
}
您需要先处理原始图像,然后才能覆盖它。