C#-删除位图填充 [英] C# - Remove Bitmap padding

查看:135
本文介绍了C#-删除位图填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以消除每条扫描线由24位位图生成的填充.

I was wondering if there's a way in order to remove the padding generated by the 24 bit Bitmap for each scan line.

我的意思是这样的:

原始[纯青色24位BMP]:

Original [Pure Cyan 24 Bit BMP] :

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

所需的输出[已删除的填充]:

Desired output [Removed Padding] :

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整除时,很有可能获得填充.

No, you'll have to remove it yourself. Padding is added to ensure that the start of a scanline in the bitmap starts at a multiple of 4. So getting padding is pretty likely when the pixel format is 24bpp, bmp_bitmap.Width * 3 is only divisible by 4 by accident.

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

You'll need a loop to copy each line. Something like this:

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);
}

这篇关于C#-删除位图填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆