我在C ++中有Mat
,这是我的形象
我使用OpenCV
进行了一些操作,现在想将它发送到我的C#项目并将其用作ImageSource
。
但是当我想在c#中调用转换器时,要将其转换为ImageSource
,我会在bitmapObj.Save
上遇到此错误:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
我的示例C ++源代码是:
Bitmap^ SomeClass::Test(System::String^ imgFileName)
{
auto fileName = msclr::interop::marshal_as<string>(imgFileName);
Mat img = imread(fileName);
auto bmp = gcnew Bitmap(img.cols, img.rows, img.step, Imaging::PixelFormat::Format24bppRgb, (IntPtr)img.data);
img.release();
return bmp;
}
我的样本c#代码是:
private void ImageTester(object sender, RoutedEventArgs e)
{
var image = testClass.Test("test.png");
bg.Source = ConvertToBitmapImageFromBitmap(image);
}
public static BitmapImage ConvertToBitmapImageFromBitmap(Bitmap btm)
{
using(var ms = new MemoryStream())
{
btm.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bImg = new BitmapImage();
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(ms.ToArray());
bImg.EndInit();
return bImg;
}
}