c#裁剪特定像素的图像

时间:2015-07-26 19:23:40

标签: c# image pointers

我想仅在特定部分裁剪完整图像中的图像这是我的代码

    private unsafe Bitmap GetDiffBitmap(Bitmap bmp)
    {

        BitmapData bmDataRes;
        bmpRes = new Bitmap(bmp.Width, bmp.Height);

        bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);

        bmDataRes = bmpRes.LockBits(new Rectangle(0, 0, bmpRes.Width, bmpRes.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

        IntPtr scan0 = bmData.Scan0;

        IntPtr scan0Res = bmDataRes.Scan0;


        int stride = bmData.Stride;

        int strideRes = bmDataRes.Stride;

        int nWidth = bmp.Width;
        int nHeight = bmp.Height;

        for(int y = 0; y < nHeight; y++)

        {

            byte* p = (byte*)scan0.ToPointer();
            p += y * stride;

            byte* pRes = (byte*)scan0Res.ToPointer();
            pRes += y * strideRes;

            for (int x = 0; x < nWidth; x++)
            {
                //always get the complete pixel when differences are found
                if (p[0] ==255)
                {
                          pRes[0] = p[0];
                    pRes[1] = p[1];
                    pRes[2] = p[2];

                    //alpha (opacity)
                    pRes[3] = p[3];
                }

                else
                {



                    bmpRes.UnlockBits(bmDataRes);

                    break;


                }


                p += 4;

                pRes += 4;
            }

        }


        return bmpRes;


    }

正如你所看到的,我只想在红色字节为255时复制像素,如果没有,则可以立即停止和中断。我想找到连续的红色部分。 但是当我发布位图时,我在该行上得到了一个奇怪的例外 bmpRes.UnlockBits(bmDataRes);异常 - A generic error occurred in GDI+ 知道为什么会抛出该错误?

1 个答案:

答案 0 :(得分:0)

你也应该打破外部bmpRes.UnlockBits(bmDataRes); break; 循环。

实际情况是,你不止一次尝试UnlockBits。

或者更简单地说,您可以更改

bmpRes.UnlockBits(bmDataRes);
return bmpRes;

mmtool/pom.xml