彩色 Bitmap转换HObject图像
之前已有的代码是这样的
public static HImage Bitmap2HImage_24(Bitmap bImage)
{
lock (m_lock)
{
Bitmap bImage24;
BitmapData bmData = null;
Rectangle rect;
IntPtr pBitmap;
IntPtr pPixels;
HImage hImage = new HImage();
rect = new Rectangle(0, 0, bImage.Width, bImage.Height);
bImage24 = new Bitmap(bImage.Width, bImage.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bImage24);
g.DrawImage(bImage, rect);
g.Dispose();
bmData = bImage24.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
pBitmap = bmData.Scan0;
pPixels = pBitmap;
hImage.GenImageInterleaved(pPixels, "bgr", bImage.Width, bImage.Height, -1, "byte", 0, 0, 0, 0, -1, 0);
bImage24.UnlockBits(bmData);
return hImage;
}
}
但是发现有问题,变换的图像十分异常,
后来查找原因,分析原因,发现是因为Bitmap4字节对齐,非4的整数倍宽度的图像,后面会补0来达到4的倍数。如图像width=202,每行202个字节,实际内存每行后面会补两个字节,宽度变为204个字节。所以重新修改转换代码,在每个末尾进行添加,这部分添加完毕后,经过测试,OK
代码如下
public static void Bmp2HObject3(Bitmap bmp, out HObject image)
{
try
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
byte[] r = new byte[srcBmpData.Height * srcBmpData.Width];
byte[] g = new byte[srcBmpData.Height * srcBmpData.Width];
byte[] b = new byte[srcBmpData.Height * srcBmpData.Width];
IntPtr ptr1 = Marshal.UnsafeAddrOfPinnedArrayElement(r, 0);
IntPtr ptr2 = Marshal.UnsafeAddrOfPinnedArrayElement(g, 0);
IntPtr ptr3 = Marshal.UnsafeAddrOfPinnedArrayElement(b, 0);
unsafe
{
byte* pIn = (byte*)(srcBmpData.Scan0.ToPointer());
for (int y = 0; y < srcBmpData.Height; y++) //列扫描
{
for (int x = 0; x < srcBmpData.Width; x++) //行扫描
{
int index = y * srcBmpData.Width + x;
r[index] = pIn[0];
g[index] = pIn[1];
b[index] = pIn[2];
pIn += 3;
}
pIn += srcBmpData.Stride - srcBmpData.Width * 3;
}
}
HOperatorSet.GenImage3(out image, "byte", srcBmpData.Width, srcBmpData.Height, new HTuple(ptr3), new HTuple(ptr2), new HTuple(ptr1));
bmp.UnlockBits(srcBmpData);
}
catch (Exception ex)
{
image = null;
}
}