需要帮忙。我想调整某个图片的大小,但是当我运行此代码时,它给了我错误 {“GDI+ 中发生了一般错误。”}
private void btnPic_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Images|*.bmp;*.jpg;*.gif|All files|*.*";
if (open.ShowDialog(this) == DialogResult.OK)
{
var image = Image.FromFile(open.FileName);
var newImage = ScaleImage(image, 300, 400);
newImage.Save(@open.FileName, ImageFormat.Png);
}
}
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;
}