日期:2014-05-18  浏览次数:22064 次

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原对象本身的像素格式是不兼容这颜色格式的,也会报错。

以下代码,我测试过,没有问题:

C# code
            //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);


以下的代码是,出现问题的代码:
C# code

                        Rectangle rect = row[colIndex];
                        Bitmap cutBitmap = pic.Clone(rect, pic.PixelFormat);

监视器下的对象数据:


        pic.Width    1000    int
        pic.Height    634    int
        pic.PixelFormat    Format24bppRgb    System.Drawing.Imaging.PixelFormat
+        rect    {X = 0 Y = 0 Width = 20 Height = 20}    System.Drawing.Rectangle



第一个参数是没有出现越界值的,而第二个参数就是用回bitmap原对象的PixelForm,一样还是会出现:内存不足。

------解决方案--------------------
建议你用Graphics 类画个新图。
C# code
                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坐标……