using HalconDotNet; using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace Bro.Common.Helper { public static class HalconHelper { //[DllImport("kernel32.dll")] //static extern void CopyMemory(IntPtr dest, IntPtr source, int lentgh); public static Bitmap HObject2Bpp8(this HObject image) { HTuple hpoint, type, width, height; const int Alpha = 255; int[] ptr = new int[2]; HOperatorSet.GetImagePointer1(image, out hpoint, out type, out width, out height); Bitmap res = new Bitmap(width.I, height.I, PixelFormat.Format8bppIndexed); //Bitmap res = new Bitmap(width.I, height.I, width.I, PixelFormat.Format8bppIndexed, (IntPtr)hpoint.D); ColorPalette pal = res.Palette; for (int i = 0; i <= 255; i++) { pal.Entries[i] = Color.FromArgb(Alpha, i, i, i); } res.Palette = pal; Rectangle rect = new Rectangle(0, 0, width, height); BitmapData bitmapData = res.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); int PixelSize = Bitmap.GetPixelFormatSize(bitmapData.PixelFormat) / 8; if (width % 4 == 0) { byte[] rawData = new byte[width * height * PixelSize]; Marshal.Copy((IntPtr)hpoint.D, rawData, 0, width * height * PixelSize); Marshal.Copy(rawData, 0, bitmapData.Scan0, rawData.Length); //Buffer. CopyMemory(bitmapData.Scan0, (IntPtr)hpoint.D, width * height * PixelSize); } else { ptr[0] = bitmapData.Scan0.ToInt32(); ptr[1] = (int)hpoint.D; for (int i = 0; i < height - 1; i++) { ptr[1] += width; byte[] rawData = new byte[width * PixelSize]; Marshal.Copy((IntPtr)ptr[1], rawData, 0, width * PixelSize); Marshal.Copy(rawData, 0, (IntPtr)ptr[0], rawData.Length); //CopyMemory((IntPtr)ptr[0], (IntPtr)ptr[1], width * PixelSize); ptr[0] += bitmapData.Stride; } } res.UnlockBits(bitmapData); return res; } } }