1

I'm trying to convert a cv::Mat into a System::Drawing::Bitmap^ in c++/CLR project. I have seen a lot of examples of how to do this, but my programm throws a System.ArgumentException only at run-time, after button click.

    private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {

        cv::Mat img = cv::imread("C://picture//colors.jpg", cv::IMREAD_COLOR);

        // OK
        cv::imshow("Colors", img);
        // OK
        System::Drawing::Bitmap^ a = gcnew System::Drawing::Bitmap(img.cols, img.rows, System::Drawing::Imaging::PixelFormat::Format24bppRgb);

        System::IntPtr ptr = (System::IntPtr)img.data;

        // KO
        System::Drawing::Bitmap^ b = gcnew System::Drawing::Bitmap(img.cols, img.rows, img.step, System::Drawing::Imaging::PixelFormat::Format24bppRgb, ptr);
        pictureBox1->Image = b;
    }

The Exception:

System.ArgumentException: 'invalid parameter'.
This exception was originally thrown at this call stack:
    System.Drawing.Bitmap.Bitmap(int, int, int, System.Drawing.Imaging.PixelFormat, System.IntPtr)
    FromMatToBitmap::FromMToB::button1_Click(System::Object^, System::EventArgs^) in FromMToB.h
    System.Windows.Forms.Control.OnClick(System.EventArgs)
    System.Windows.Forms.Button.OnClick(System.EventArgs)
    System.Windows.Forms.Button.OnMouseUp(System.Windows.Forms.MouseEventArgs)
    System.Windows.Forms.Control.WmMouseUp(ref System.Windows.Forms.Message, System.Windows.Forms.MouseButtons, int)
    System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message)
    System.Windows.Forms.ButtonBase.WndProc(ref System.Windows.Forms.Message)
    System.Windows.Forms.Button.WndProc(ref System.Windows.Forms.Message)
    System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr, int, System.IntPtr, System.IntPtr)
    ...
    [Call Stack Truncated]

The problem seems the System::IntPtr ptr, but the compiler doesn't show any error.

C++/CLI Properties: Common Language Runtime Support: "Common Language Runtime Support (/clr)", .NET Target Framework Version: "v4.7.2", Enable Managed Incremental Build: "Yes"

OpenCV Version: 4.5.0

  • Does this answer your question? [Why must "stride" in the System.Drawing.Bitmap constructor be a multiple of 4?](https://stackoverflow.com/questions/2185944/why-must-stride-in-the-system-drawing-bitmap-constructor-be-a-multiple-of-4) – Lev Leontev Dec 26 '20 at 12:43

0 Answers0