领胜LDS 键盘AOI检测项目
xcd
2020-07-10 d437e53b2eea04f88217d719abc8d34ba5b25c2c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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;
        }
    }
}