首页 > 编程语言 > 详细

c#与C++dll互传图片

时间:2020-05-21 11:52:26      阅读:59      评论:0      收藏:0      [点我收藏+]

直接上代码,

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");        

 

 

c#与C++dll互传图片

原文:https://www.cnblogs.com/Betty-IT/p/12929029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!