I have a Mat
in C++ which is presents my image.
I did some operation on in with OpenCV
and now want to send it to my C# project and use it as an ImageSource
.
But when I want to call the converter in c#, to convert it to ImageSource
, I face to this error on bitmapObj.Save
:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
my sample C++ source is:
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;
}
and my sample c# code is:
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;
}
}