Skip to main content
 首页 » 编程设计

C#之删除位图填充

2024年02月13日10haluo1

我想知道是否有办法去除由 24 位位图为每个扫描线生成的填充。

我的意思是这样的:

原始 [纯青色 24 位 BMP]:

FF FF 00 FF FF 00 FF FF **00 00** FF FF 00 FF FF 00 FF FF 00 

期望的输出[删除填充]:

FF FF 00 FF FF 00 FF FF **00** FF FF 00 FF FF 00 FF FF 00 

这是我获取像素数据的代码。

            Bitmap tmp_bitmap = BitmapFromFile; 
 
            Rectangle rect = new Rectangle(0, 0, tmp_bitmap.Width, tmp_bitmap.Height); 
            System.Drawing.Imaging.BitmapData bmpData = 
                tmp_bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, 
                PixelFormat.Format24bppRgb); 
 
            int length = bmpData.Stride * bmpData.Height; 
 
            byte[] bytes = new byte[length]; 
 
            // Copy bitmap to byte[] 
            Marshal.Copy(bmpData.Scan0, bytes, 0, length); 
            tmp_bitmap.UnlockBits(bmpData); 

提前谢谢你。

请您参考如下方法:

不,您必须自己将其删除。添加填充以确保位图中扫描线的起始位置是 4 的倍数。因此,当像素格式为 24bpp 时,很可能会填充,bmp_bitmap.Width * 3 只能被 4 整除。

您需要一个循环来复制每一行。像这样:

byte[] bytes = new byte[bmpData.Width * bmpData.Height * 3]; 
for (int y = 0; y < bmpData.Height; ++y) { 
    IntPtr mem = (IntPtr)((long)bmpData.Scan0 + y * bmpData.Stride); 
    Marshal.Copy(mem, bytes, y * bmpData.Width * 3, bmpData.Width * 3); 
}