Domanda

I need to show an Image from RAM in the pictureBox. I spend my whole day yesterday to try and get it work. Here is a bit of code to show you how I am currently trying to do it, but I cannot get the System::Drawing::Bitmap to work. All I get is an empty pictureBox. I also write a BMP file to my disk and the file is just as intended (greyscale noise). I would be very happy if you could help me out!

unsigned char* imgData;
imgData = (unsigned char*)malloc(100 * 100 * sizeof(unsigned char)*3);
for (int i = 0; i < 100 * 100; i++){
     memset(imgData+ i*3,rand()%255, 3); //generates a random pixel vaoue between 0 and 255 and then assigns all three colors of a pixel to it
}
// this->textBox1->Text += "Values: " + *(imgData + 1) + " \r\n";
 const char* fname;
 fname = "test.bmp";
 write_bmp(fname, 100, 100, (char*)imgData); //writes 24-bit BMP File

 System::Drawing::Bitmap ^mybm = gcnew System::Drawing::Bitmap(
           100, 100, 100*sizeof(unsigned char)*3,
           System::Drawing::Imaging::PixelFormat::Format24bppRgb,
           (System::IntPtr) imgData);

 this->pictureBox1->Image = mybm;
 this->pictureBox1->Show();

 free(imgData);
È stato utile?

Soluzione

From MSDN topic Bitmap Constructor (Int32, Int32, Int32, PixelFormat, IntPtr):

The caller is responsible for allocating and freeing the block of memory specified by the scan0 parameter. However, the memory should not be released until the related Bitmap is released.

In your case, you release imgData array immediately after Bitmap creating. Keep this array persistent all time when Bitmap is alive, according to the constructor requirements.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top