Skip to main content
 首页 » 编程设计

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

2024年02月23日16sky-heaven

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

我可以使用 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 的代码工作正常,它只是保存我遇到问题的图像。

下面的代码定义了srcBitmap和newBitmap

    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()。