C# - Remove Bitmap padding

前端 未结 3 1859
花落未央
花落未央 2021-01-15 23:13

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

What I mean is like this :

Original [Pure

3条回答
  •  星月不相逢
    2021-01-16 00:04

    You should copy the bitmap line by line, but skip padding bytes. An extension method for that would be:

    static class BitmapExtensions
    {
        public static void RemovePadding(this Bitmap bitmap)
        {
            int bytesPerPixel = Image.GetPixelFormatSize(bitmap.PixelFormat) / 8;
    
            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
            var pixels = new byte[bitmapData.Width * bitmapData.Height * bytesPerPixel];
    
            for (int row = 0; row < bitmapData.Height; row++)
            {
                var dataBeginPointer = IntPtr.Add(bitmapData.Scan0, row * bitmapData.Stride);
                Marshal.Copy(dataBeginPointer, pixels, row * bitmapData.Width * bytesPerPixel, bitmapData.Width * bytesPerPixel);
            }
    
            Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
            bitmap.UnlockBits(bitmapData);
        }
    }
    

提交回复
热议问题