c#和c++相互傳遞圖片資料
阿新 • • 發佈:2018-11-28
本文章由@默茉 出品,轉載請註明出處。
C#傳資料到c++,需要編譯c++的dll庫,這裡不具體介紹如何編譯dll庫。
C#:
- 宣告介面
[DllImport("dllmake")]
private unsafe static extern bool detectAndDraw(byte[] ImageBuffer, byte[] ImageBuffer1, int imageWeidth, int imageHeight, byte[] data);
- 呼叫介面
bool flag = detectAndDraw(rgbValues, rgbValues1, ImageWeidth, ImageHeight, pstdata);
- 將圖片讀成byte[]
注:不能直接用IO將圖片讀成byte[]陣列,如果直接用IO都城陣列,那傳過去的資料將不能生成一幅圖片,需要藉助c#的整合庫(System.Drawing.dll), ## System.Drawing.dll
Bitmap bmp = (Bitmap)Image.FromFile("src.jpg"); Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * bmp.Height; byte[] rgbValues = new byte[bytes]; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); int ImageWeidth = bmp.Width; int ImageHeight = bmp.Height;
c++
- 宣告可調的介面
DLLMAKE_API bool detectAndDraw(char* defaultphoto, char* backgroundphoto, int imageWeidth, int imageHeight, char* pst);
**
注:
**
經過本次實驗,c#的資料用byte【】封裝,c++ 用char就可以接收,同樣對c++的char賦值等同對C#的byte【】陣列進行賦值,所以只要在c++裡把圖片的畫素點賦值給char*,就可以在c#裡用相應的byte【】數組裡面的資料生成圖片。