1. 程式人生 > >相機SDK取像獲取halcon資料型別格式

相機SDK取像獲取halcon資料型別格式

當我們使用相機SDK採集影象時,得到的往往是Bitmap影象,在這給大家分享一下自己寫的Bitmap如何轉換成HImage的程式碼,希望能幫到大家。

    /// <summary> 
    /// 彩色圖Bitmap轉換成HImage 
    /// </summary> 
    /// <param name="bImage"></param> 
    /// <returns></returns> 
    HImage Bitmap2HImage_24(Bitmap bImage) 
    { 
        Bitmap bImage24; 
        BitmapData bmData = null; 
        Rectangle rect; 
        IntPtr pBitmap; 
        IntPtr pPixels; 
        HImage hImage = new HImage(); 


        rect = new Rectangle(0, 0, bImage.Width, bImage.Height); 
        bImage24 = new Bitmap(bImage.Width, bImage.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bImage24); 
        g.DrawImage(bImage, rect); 
        g.Dispose(); 


        bmData = bImage24.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); 
        pBitmap = bmData.Scan0; 
        pPixels = pBitmap; 


        hImage.GenImageInterleaved(pPixels, "bgr", bImage.Width, bImage.Height, -1, "byte", 0, 0, 0, 0, -1, 0); 


        bImage24.UnlockBits(bmData); 


        return hImage; 
    } 


    /// <summary> 
    /// Bitmap轉換成HImage 
    /// </summary> 
    /// <param name="bImage"></param> 
    /// <returns></returns> 
    HImage Bitmap2HImage_8(Bitmap bImage) 
    { 
        Bitmap bImage8; 
        BitmapData bmData = null; 
        Rectangle rect; 
        IntPtr pBitmap; 
        IntPtr pPixels; 
        HImage hImage = new HImage(); 


        rect = new Rectangle(0, 0, bImage.Width, bImage.Height); 
        bImage8 = new Bitmap(bImage.Width, bImage.Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); 
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bImage8); 
        g.DrawImage(bImage, rect); 
        g.Dispose(); 


        bmData = bImage8.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); 
        pBitmap = bmData.Scan0; 
        pPixels = pBitmap; 


        hImage.GenImage1("byte", bImage.Width, bImage.Height, pPixels); 


        bImage8.UnlockBits(bmData); 


        return hImage; 
    }