【C#】Halcon显示图像(读文件路径、缓存、创建空白图像)

public HTuple hv_ExpDefaultWinHandle;

  //输入图像宽高
  Int64 Input_Image_Width = 0, Input_Image_Height = 0;

  /// <summary>
  /// 加载图像
  /// </summary>
  ///  <param name="type">类型,0:内存地址; 1:文件路径;2:图像; 3:空白图像</param>
  /// <param name="ptr">内存地址</param>
  /// <param name="filePath">文件路径</param>
  /// <exception cref="Exception"></exception>
  private void action(int type, IntPtr ptr, String filePath = "")
  {
      try
      {
          HObject ho_Image;
          HOperatorSet.GenEmptyObj(out ho_Image);
          HTuple win_Width, win_Height, win_Col, win_Row;
          HOperatorSet.GetWindowExtents(hv_ExpDefaultWinHandle, out win_Row, out win_Col, out win_Width, out win_Height);//获取窗体大小规格

          //设置画图颜色
          HOperatorSet.SetDraw(hv_ExpDefaultWinHandle, "margin");
          HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "red");
          //设置窗体显示对象个数
          HOperatorSet.SetWindowParam(hv_ExpDefaultWinHandle, "graphics_stack_max_element_num", 500000);

          if (type == 0 || type == 1)
          {
              if (!string.IsNullOrEmpty(filePath))
              {
                  //文件路径加载图像
                  HOperatorSet.ReadImage(out ho_Image, filePath);
              }
              else if (ptr != IntPtr.Zero)
              {
                  //内存加载图像
                  HOperatorSet.GenImage1(out ho_Image, "byte", Input_Image_Width, Input_Image_Height, ptr);
              }
          }
          else if (type == 3)
          {
              //创建黑色空白图像
              HOperatorSet.GenImageConst(out ho_Image, "byte", Input_Image_Width, Input_Image_Height);
          }

          //LogHelperUtility.Info("结束畸变:" + DateTime.Now.ToLongTimeString());
          HTuple Width, Height;
          HOperatorSet.GetImageSize(ho_Image, out Width, out Height);  // 获取图像宽高

          HTuple ScaleWidth = Width / (win_Width * 1.0);
          HTuple ScaleHeight = Height / (win_Height * 1.0);

          HTuple row1, column1, row2, column2;
          row1 = 0;
          column1 = -(1.0) * ((win_Width * ScaleHeight) - Width) / 2;
          row2 = row1 + win_Height * ScaleHeight;
          column2 = column1 + win_Width * ScaleHeight;
          HOperatorSet.SetPart(hv_ExpDefaultWinHandle, row1, column1, row2, column2);
          // 关键
          HOperatorSet.ClearWindow(hv_ExpDefaultWinHandle);
          HOperatorSet.DispObj(ho_Image, hv_ExpDefaultWinHandle);
      }
      catch (Exception ex)
      {
          throw new Exception("[action]图像加载失败,ex:" + ex.Message);
      }
  }
posted @ 2024-09-27 09:04  qiutian-hao  阅读(90)  评论(0编辑  收藏  举报