C# Bitmap.Clone 方法,提示内存不足
我独单的写一些测试。
测试过,发现提示内存不足的情况有两种:
以下内容中:bitmap原对象:bm.Clone(...),这时bm就是bitmap原对象
1、就是Clone第一个参数:Rectangle的:X,Y,Width,Height的值,如果相对于bitmap原对象来说,
都是越界值(X,Y出现负数,或是X,Y大于bitmap的宽高;Width,Heigth相对X,Y坐标截图后过大)
2、就是Clone第二个参数:PixelForm,如果bitmap原对象本身的像素格式是不兼容这颜色格式的,也会报错。
以下代码,我测试过,没有问题:
//Bitmap bm = (Bitmap)Image.FromFile(@"Pic/WEB Study.jpg");
//Bitmap bSp = bm.Clone(new System.Drawing.Rectangle(0, 0, 1, 1), bm.PixelFormat);
//bSp.Save(@"MyCutPicturesExport/WEB Study.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Rectangle rect = row[colIndex];
Bitmap cutBitmap = pic.Clone(rect, pic.PixelFormat);
监视器下的对象数据:
pic.Width1000int
pic.Height634int
pic.PixelFormatFormat24bppRgbSystem.Drawing.Imaging.PixelFormat
+rect{X = 0 Y = 0 Width = 20 Height = 20}System.Drawing.Rectangle
using (Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb))
{
bmp.SetResolution(imageFrom.HorizontalResolution, imageFrom.VerticalResolution);
using (Graphics g = Graphics.FromImage(bmp))
{
// 用白色清空
g.Clear(Color.White);
// 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// 指定高质量、低速度呈现。
g.SmoothingMode = SmoothingMode.HighQuality;
// 在指定位置并且按指定大小绘制指定的 Image 的指定部分。
g.DrawImage(imageFrom, new Rectangle(X, Y, width, height), new Rectangle(0, 0, imageFromWidth, imageFromHeight), GraphicsUnit.Pixel);
}
}