[英]Error saving resized image
我有以下代码
int oswidth = 0;
int osheight = 0;
if (comboBox3.SelectedIndex == 0)
{
oswidth = Convert.ToInt32(textBox5.Text.ToString());
osheight = Convert.ToInt32(textBox6.Text.ToString());
}
else if (comboBox3.SelectedIndex == 1)
{
oswidth = 38 * Convert.ToInt32(textBox5.Text.ToString());
osheight = 38 * Convert.ToInt32(textBox6.Text.ToString());
}
Bitmap oldimg = new Bitmap(pictureBox3.Image);
Bitmap objBitmap = new Bitmap(oldimg, new Size(oswidth, osheight));
objBitmap.Save(pictureBox3.ImageLocation.ToString(), ImageFormat.Jpeg);
问题是,当所选索引为0时,它可以正常工作,但是当所选索引为1时,出现错误“参数无效”。
我尝试了不同的图像,但相同的错误。 是32乘以吗
尝试创建位图时,“ Parameter is not valid
错误消息通常表示您正在尝试为其分配过多的内存。 该位图需要bit-depth*width*height/8
字节的连续内存,而没有足够的内存来满足此需求。
在这种情况下,看起来就像是因为您将其尺寸乘以38(因此将内存中的尺寸乘以38 ^ 2)。
您可以利用以下方法:
private static void ResizeImage(string file, double vscale, double hscale, string output)
{
using(var source = Image.FromFile(file))
{
var width = (int)(source.Width * vscale);
var height = (int)(source.Height * hscale);
using(var image = new Bitmap(width, height, PixelFormat.Format24bppRgb))
using(var graphic = Graphics.FromImage(image))
{
graphic.SmoothingMode = SmoothingMode.AntiAlias;
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.DrawImage(source, new Rectangle(0, 0, width, height));
image.Save(output);
}
}
}
您可以根据自己的喜好定制它,但它应该可以满足您的需求。
重要: vscale
和hscale
分开的原因是不遵循缩放。 您可以轻松地将它们组合在一起,以便进行相应的缩放。 要记住的另一件事是您使用的值为32
。 尝试使用.32
的值,它将更像一个百分比,它将按比例缩放。 同样,它也不会显着增加导致错误的内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.