c++和c#项目进行图片数据交互

本文介绍了如何在C#项目中引入C++编写的dll库,并展示了如何通过DllImport调用C++函数处理图片数据,包括内存交互、JPEG图片转换和返回数据的处理过程。

1、c#项目中引入c++代码的dll库代码

[DllImport("ImageStitchingV2.dll", EntryPoint = "ImageCon",CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr ImageCon(IntPtr image,int h,int w,int cam,bool is_h,int method,out int out_h,out int out_w);

说明:[DllImport("{dll库名称}", EntryPoint = "{需要导入的函数名称}",CallingConvention = {导入解析格式})]

public static extern {函数返回值}  {函数名称}({参数});

图片数据在内存中进行交互时,在c#项目中一般使用Inptr类型接收和传递;c++中使用int*接收,传出时可以使用uchar*传出。

2、c#项目中进行图片转换

该步骤可根据实际情况进行转换,本文是将jpeg图片进行转换

//读取图片
Image<Bgr, byte> im = new Image<Bgr, byte>("E://img//up_13.jpeg");
//构建存放数据IntPtr 
IntPtr im_ptr = new IntPtr();
int stdp = 0;
Size size = new Size();
//将图片内容进行内存转换
CvInvoke.cvGetRawData(im, out im_ptr, out stdp, out size);
//将数据传给dll库
//定义输出数据的宽和高,和数据内容
int out_h;
int out_w;
IntPtr out_img1;
//函数传入时,需要包含数据内容和数据宽高,返回时也需要返回数据的内容和宽高
out_img1 = ImageCon(im_ptr, size.Height, size.Width, 0, false,0, out out_h, out out_w);
//创建内存空间,存放返回的图片数据
byte[] out_img11 = new byte[out_h * out_w * 3];
int sizeOfOutImg11 = out_img11.Length * sizeof(byte);
int sizeOfOutImg1 = Marshal.SizeOf(out_img1); // 获取 IntPtr 大小
//内存数据拷贝
Marshal.Copy(out_img1, out_img11, 0, out_img11.Length);

Bitmap bitmap = new Bitmap(out_w, out_h, PixelFormat.Format24bppRgb);
// 将 IntPtr 中的数据拷贝到 Bitmap 对象		IsAbstract	false	bool
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, out_w, out_h), ImageLockMode.WriteOnly, bitmap.PixelFormat);
Marshal.Copy(out_img11,0, bmpData.Scan0, out_img11.Length); // 3 表示 24 位彩色图像
bitmap.UnlockBits(bmpData);
// 保存图像到本地文件
bitmap.Save("output.jpg", ImageFormat.Jpeg);
bitmap2.Save("output2.jpg", ImageFormat.Jpeg);
// 最后,记得释放资源
bitmap.Dispose();
bitmap2.Dispose();

3、c++中接收和返回图片数据代码

3.1、C++中对应函数的定义:

uchar* ImageCon (int* image_buffer,int img_height,int img_width,int cam_num,bool is_vertically_con,int vertically_stitcher_method,int& out_h,int& out_w);

参数介绍:

int* image_buffer--传入的数据内存地址

int img_height--传入图片高度

img_width--传入图片宽度

int& out_h--函数输出图片的高度

int& out_w--函数输出图片的宽度

函数返回uchar*,是存放数据的地址

3.2、c++中函数实现:

  1. 将int*数据转换为Mat类型,使用opencv中的Mat可以转换

cv::Mat img_from_buffer = cv::Mat(img_height, img_width, CV_8UC3, image_buffer);

注意:CV_8UC3会转换成3通道彩色图片,具体传入图片通道数需要提前约定好,

  1. 将处理完数据返回

uchar* TransImage2Buffer(cv::Mat img,  int& out_h, int& out_w)

{  

    if (img.empty())

    {

        return nullptr;    }

    try

    {   

        out_w = img.cols;

        out_h = img.rows;

        return img.data;

    }

    catch (const std::exception& e)

    {

        return nullptr;

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值