【问题标题】:Drawing Bitmap with unsafe per pixel access results in empty image使用不安全的每像素访问绘制位图会导致空图像
【发布时间】:2011-02-27 20:34:29
【问题描述】:

我有一个类通过读取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。另请注意,您保存的是 PNG,而不是 JPEG。并使用 Bitmap(int, int, PixelFormat) 构造函数。并使用 x 来迭代宽度,而不是高度。
  • 感谢构造函数的提示,迭代器将被修复...这只是一个快速破解。

标签: c# .net graphics bitmap gdi+


【解决方案1】:

您需要UnlockBits()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2018-06-16
    • 2015-11-12
    • 2019-08-07
    • 1970-01-01
    • 2019-09-17
    • 2013-02-20
    相关资源
    最近更新 更多