将Hobject或HImage图像转为Bitmap格式(C#)

将Hobject或HImage图像转为Bitmap格式(C#)
项目上的需求,需要将Halcon处理过的图像转换为Bitmap格式的图像进行显示保存。在网上查阅了一些例程,多数都未能实现。在探讨摸索下,结合网上查阅到的类似程序,最终实现了Hobject或Himage转Bitmap的功能。
贴代码之前首先介绍一下转换的核心算子:GetImagePointer1。
IntPtr HImage.GetImagePointer1(out string type,out int width,out int height),这是halcon图像库中获取黑白图像数据指针的算子,再次强调,是获取黑白图像数据指针的算子。该算子返回一个指向图像数据的IntPtr型指针,输出的type参数为数据格式,例如图像为8位黑白格式的时候type为“byte”,width和height是图像的尺寸。
下面是转换的代码

	Himage image = new HImage();
    image.ReadImage(@"d:\image.bmp");//读取图像
    HImage grayImage = new HImage();
    grayImage = image.Rgb1ToGray();//将彩色图像转为黑白
    string type;//接收图像类型
    int width,height;//接收图像尺寸
    IntPtr pointer=grayImage.GetImagePointer1(out type, out width, out height);
    System.Drawing.Imaging.ColorPalette palette = null;
    System.Drawing.Bitmap bitmap = null;
    System.Drawing.Bitmap curBitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
    System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
    System.Drawing.Imaging.BitmapData imageData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, curBitmap.PixelFormat);
    int PixelSize = System.Drawing.Bitmap.GetPixelFormatSize(imageData.PixelFormat) / 8;
    //定义用于存储图像数据的Buffer
    byte[] buffer = new byte[curBitmap.Width * curBitmap.Height];
    //将图像数据复制到Buffer内
    System.Runtime.InteropServices.Marshal.Copy(pointer, buffer, 0, buffer.Length);
    unsafe
    {
        //使用不安全代码
        fixed (byte* bytePointer = buffer)
        {
             bitmap = new System.Drawing.Bitmap(curBitmap.Width, curBitmap.Height, curBitmap.Width, System.Drawing.Imaging.PixelFormat.Format8bppIndexed, new IntPtr(bytePointer));
             palette = bitmap.Palette;
             for (int Index = 0; Index <= byte.MaxValue; Index++)
             {
                  palette.Entries[Index] = System.Drawing.Color.FromArgb(byte.MaxValue, Index, Index, Index);
             }
            bitmap.Palette = palette;
            bitmap.Save(@"d:\bitmap.bmp");
        }
    }

由于程序中使用到了不安全代码,所以需要在项目中进行相应的设置:
1.在项目上点击鼠标右键—属性。
在这里插入图片描述
2.选择生成一栏,勾选“允许不安全代码”。OK。
在这里插入图片描述

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值