读书人

C# Bit地图.Clone 方法提示内存不足

发布时间: 2013-12-28 22:19:34 作者: rapoo

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


第一个参数是没有出现越界值的,而第二个参数就是用回bitmap原对象的PixelForm,一样还是会出现:内存不足。
[解决办法]
建议你用Graphics 类画个新图。
                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);

}
}

[解决办法]
引用:
我独单的写一些测试。

测试过,发现提示内存不足的情况有两种:

以下内容中:bitmap原对象:bm.Clone(...),这时bm就是bitmap原对象

1、就是Clone第一个参数:Rectangle的:X,Y,Width,Height的值,如果相对于bitmap原对象来说,
都是越界值(X,Y出现负数,或是X,Y大于bitmap的宽高;Width,Heigth相对X,Y坐标……

Bitmap.Clone提示内存不足的错误的话
1.使用Rectangle对象时超出了图像的大小范围。
2.在指定图像的颜色数据格式(PixelFormat)时,生成的颜色数据格式与原图的数据格式不一致也将导致这个错误的出现.比如一张JPG的图片,保存是使用PixelFormat.Format8bppIndexed就会出现这样的错误。

读书人网 >C#

热点推荐