我得到了一些从数据库中检索图像的代码,然后调整它的大小以在某些页面上显示。但是,我在某些图像上收到“内存不足”错误。
在我目前的情况下,我只在一张图像上得到它,其余图像工作正常。
请在下面查看我的代码。我错过了什么吗?我没有正确释放对象吗?还是我的一些使用语句应该改进?canvas.DrawImage 行给出了错误。在我的代码中查找错误的任何帮助将不胜感激。
平台构建是:任何 CPU 我的操作系统:Win 7 64bit
private byte[] SaveResizedImage(byte[] origImageBytes, int targetSize)
{
using (MemoryStream ms = new MemoryStream(origImageBytes))
using (Image origImage = Image.FromStream(ms))
{
Size newSize = CalculateDimensions(origImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(origImage, new Rectangle(new Point(0, 0), newSize)); <--- This line give the exception error
ImageCodecInfo codecInfo = GetEncoderInfo(ImageFormat.Jpeg);
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 75L);
using (MemoryStream newms = new MemoryStream())
{
newImage.Save(newms, codecInfo, encoderParams);
return newms.ToArray();
}
}
}
}
public static ImageCodecInfo GetEncoderInfo(ImageFormat format)
{
return ImageCodecInfo.GetImageEncoders().ToList().Find(delegate(ImageCodecInfo codec)
{
return codec.FormatID == format.Guid;
});
}
private static Size CalculateDimensions(Size oldSize, int targetSize)
{
Size newSize = new Size();
if (oldSize.Height > oldSize.Width)
{
newSize.Width = (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
newSize.Height = targetSize;
}
else
{
newSize.Width = targetSize;
newSize.Height = (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
}
return newSize;
}
谢谢