HObject转Bitmap


该方法非本人原创,此为记录之用;具体出处已经忘记,若有知道的,麻烦说一下,后续标明转载之处。


需要引用以下命名空间

using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using HalconDotNet;

在类的内部添加以下方法

[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int memcpy(IntPtr dst, IntPtr src, int bytes);

具体转换过程

public static Bitmap CvtHObj2Bmp(HObject vImg)
{
	Bitmap tBmp;
	HTuple hpoint, type, width, height;
	const int Alpha = 255;
	IntPtr[] ptr = new IntPtr[2];
	HOperatorSet.GetImagePointer1(vImg, out hpoint, out type, out width, out height);

	tBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
	ColorPalette pal = tBmp.Palette;
	for (int i = 0; i <= 255; i++)
	{
		pal.Entries[i] = Color.FromArgb(Alpha, i, i, i);
	}
	tBmp.Palette = pal;
	Rectangle rect = new Rectangle(0, 0, width, height);
	BitmapData bitmapData = tBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
	int PixelSize = Bitmap.GetPixelFormatSize(bitmapData.PixelFormat) / 8;
	ptr[0] = bitmapData.Scan0;
	ptr[1] = hpoint;
	if (width % 4 == 0)
	{
		memcpy(ptr[0], ptr[1], width * height * PixelSize);
	}   
	else
	{
		for (int i = 0; i < height - 1; i++)
		{
			ptr[1] = (ptr[1].ToInt64() + width);
			memcpy(ptr[0], ptr[1], width * PixelSize);
			ptr[0] += bitmapData.Stride;
		}
	}
	tBmp.UnlockBits(bitmapData);
	return tBmp;
}

你可能感兴趣的:(C#)