如何从负步幅位图复制的像素数据? [英] How can I copy the pixel data from a Bitmap with negative stride?
问题描述
我一直在寻找一个位图转换为8bpp的最快方法。
我发现2种方式:
I was looking for the fastest way to convert a Bitmap to 8bpp. I found 2 ways:
1
public static System.Drawing.Image ConvertTo8bpp(Bitmap oldbmp)
{
using (var ms = new MemoryStream())
{
oldbmp.Save(ms, ImageFormat.Gif);
ms.Position = 0;
return System.Drawing.Image.FromStream(ms);
}
}
2 http://www.wischik.com /lu/programmer/1bpp.html
但是:
1 在一个非常低质量的结果,结果(坏托盘)
But: 1. Results in a very low quality result (bad pallet)
和 2 给我负步幅位图,当我尝试lockbits和数据复制到一个字节数组我得到一个异常:尝试读取或写入受保护的内存。这通常是指示其他内存已损坏。的
and 2 gives me a Bitmap with negative stride, when I try to lockbits and copy the data to a byte array I get an exception: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
this.stride = bmpData.Stride;
this.bytesPerPixel = GetBytesPerPixel(bmp.PixelFormat);
int length = bmpData.Stride * bmp.Height;
if (this.stride < 0)
this.data = new byte[-length];
else
this.data = new byte[length];
Marshal.Copy(bmpData.Scan0, data, 0, length);
//Unlock the bitmap
bmp.UnlockBits(bmpData);
我怎样才能让 2 给出了肯定的步伐?或者我如何可以复制使用负箭步lockbits数据??
How can I make 2 gives a positive stride? Or how can I copy data using lockbits of a negative stride??
推荐答案
复制1个排的时间,计算行的起始指针((BYTE *)SCAN0 +(Y *步幅) )
。的code将是正或负的步幅相同。
Copy 1 row at a time, calculating the starting pointer for a row as ((byte*)scan0 + (y * stride))
. The code will be identical for either positive or negative stride.
这篇关于如何从负步幅位图复制的像素数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!