I wrote this sample code to explain my problem. I have a solution in VS 2013, contains one C# project and a C++ project. I try to read an image with OpenCV in C++ (x86). and want to pass in to a C# x86 project (used CLR mode) to a Bitmap Object and Then BitmapImage Object to use as a WPF ImageSource.
My C++ Code:
Bitmap^ SomeClass::Test(System::String^ imgFileName)
{
auto fileName = msclr::interop::marshal_as<string>(imgFileName);
Mat img = imread(fileName);
//Do something
auto bmp = gcnew Bitmap(img.cols, img.rows, img.step, Imaging::PixelFormat::Format24bppRgb, (IntPtr)img.data);
bmp->Save("InC++Side.png");
return bmp;
}
My C# Code:
private void ImageTester(object sender, RoutedEventArgs e)
{
var image = testClass.Test("test.png");
image.Save("InC#Side.png");
bg.Source = ConvertToBitmapImageFromBitmap(image);
}
public static BitmapImage ConvertToBitmapImageFromBitmap(Bitmap image)
{
using(var ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bImg = new BitmapImage();
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(ms.ToArray());
bImg.EndInit();
return bImg;
}
}
Problem is that the file saved by C++ (InC++Side.png) is perfect; but the other one which is presented the Bitmap object in C# is just a gray rectangle with that image's Height and Width.
Where is the problem?
How I can pass the Image to my C# project?