c#與C++dll互傳圖片


直接上代碼,

public static BitmapInfo GetImagePixel(Bitmap Source)
        {
            byte[] result;
            int step;
            int iWidth = Source.Width;
            int iHeight = Source.Height;
            //
            if (iWidth %4!=0)
            {
                iWidth = iWidth - (iWidth % 4);
            }
            Rectangle rect = new Rectangle(0, 0, iWidth, iHeight);
            System.Drawing.Imaging.BitmapData bmpData = Source.LockBits(rect,
                System.Drawing.Imaging.ImageLockMode.ReadWrite, Source.PixelFormat);
            IntPtr iPtr = bmpData.Scan0;
            //int iBytes = iWidth * iHeight * 3;
            step = bmpData.Stride/iWidth;
            int iBytes = iWidth * iHeight * step;
            byte[] PixelValues = new byte[iBytes];
            System.Runtime.InteropServices.Marshal.Copy(iPtr, PixelValues, 0, iBytes);
            Source.UnlockBits(bmpData);
            result = PixelValues;
            BitmapInfo bi = new BitmapInfo { Result = result, Channels = step, width =iWidth, height = iHeight};
            return bi;
        }
        public static Bitmap SetImagePixel(ref Bitmap Source,byte[] imgData,int iWidth, int iHeight, int step)
        {
            byte[] result;
            //
            if (iWidth % 4 != 0)
            {
                iWidth = iWidth - (iWidth % 4);
            }
            Rectangle rect = new Rectangle(0, 0, iWidth, iHeight);
            System.Drawing.Imaging.BitmapData bmpData = Source.LockBits(rect,
                System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            IntPtr iPtr = bmpData.Scan0;
            //int iBytes = iWidth * iHeight * 3;
            int iBytes = iWidth * iHeight * step;
            //byte[] PixelValues = new byte[iBytes];
            //bmpData.Scan0 = System.Runtime.InteropServices.Marshal.AllocHGlobal(iBytes);  //這句代碼必須刪除,否則會出現內存問題
            System.Runtime.InteropServices.Marshal.Copy(imgData, 0, bmpData.Scan0, iBytes);

            Source.UnlockBits(bmpData);
            result = imgData;
           // BitmapInfo bi = new BitmapInfo { Result = result, Channels = step, width = iWidth, height = iHeight };
            return Source;
        }
BitmapInfo 類定義
public class BitmapInfo
    {
        public byte[] Result { get; set; }
        public int Channels { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }

看到網上所有方法都只有c#傳圖片給c++, 卻沒有從c++獲取圖片后,怎么轉回來,因此研究了代碼后,寫了

SetImagePixel()方法,此方法經測試有效,調用實例如下:
          Bitmap b = new Bitmap(bitmap.width, bitmap.height);
            GetImagePixel(ref b,bitmap.Result, bitmap.width, bitmap.height, bitmap.Channels);
            b.Save("D:\\hhh.jpg");        

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM