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");        
 
原文地址:https://www.cnblogs.com/Betty-IT/p/12929029.html