繁体   English   中英

使用不安全的每像素访问绘制位图会导致空图像

[英]Drawing Bitmap with unsafe per pixel access results in empty image

我有一个类通过读取Bitmap创建一个Color值矩阵。 该类使用指向图像的指针直接读取unsafe块内的像素中的每个字节。 该类的目的是将像素值读入内存,然后在将图像保存为新文件之前可以对其运行过滤器。

我可以使用GDI +的setPixel()方法重新创建图像,但是它对我的需求来说太慢了。

我正在尝试使用以下函数保存新的图像文件:

    public void saveImageFromPixels()
    {

        this.newBitmap = new Bitmap(srcBitmap.Width, srcBitmap.Height);

        BitmapData imgData = newBitmap.LockBits(new Rectangle(0, 0, newBitmap.Width, newBitmap.Height),
                                                ImageLockMode.ReadWrite,
                                                PixelFormat.Format24bppRgb);

        int stride = imgData.Stride;
        System.IntPtr Scan0 = imgData.Scan0;

        unsafe
        {
            byte* p = (byte*)(void*)Scan0;
            int nOffset = stride - newBitmap.Width * 3;

            for (int x = 0; x < newBitmap.Height; ++x)
            {

                for (int y = 0; y < newBitmap.Width; ++y)
                {
                    p[0] = (byte)(255 - matrix[y][x].B);
                    p[1] = (byte)(255 - matrix[y][x].G);
                    p[2] = (byte)(255 - matrix[y][x].R);
                    p += 3;
                }
                p += nOffset;
            }


        }

        this.newBitmap.Save(@"C:\images\1-d.jpg");
    }

但结果是空图像(具有适当的尺寸)。 直接访问像素并将值保存为Color工作正常,它只是保存我遇到问题的图像。

以下代码定义了srcBitmapnewBitmap

    private Bitmap srcBitmap;
    private Bitmap newBitmap;
    private List<List<Color>> matrix;

    public PixelMatrix(string path)
    {

        this.srcBitmap = new Bitmap(path);

        this.matrix = new List<List<Color>>(srcBitmap.Width);

        for (int x = 0; x < srcBitmap.Width; x++)
        {
            this.matrix.Add(new List<Color>(srcBitmap.Height));
        }

    }

你需要UnlockBits()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM