24

Is it possible to load a picture from memory (byte[] or stream or Bitmap) without saving it to disk?

This is the code I use to turn the byte[] array into a Bitmap:

unsafe
{
    fixed (byte* ptr = Misc.ConvertFromUInt32Array(image))
    {
        Bitmap bmp = new Bitmap(200, 64, 800, PixelFormat.Format32bppRgb, new IntPtr(ptr));
        bmp.RotateFlip(RotateFlipType.Rotate180FlipX);
        bmp.MakeTransparent(Color.Black);
        bmp.Save("test.bmp");
    }
}

Instead of using Bmp.save(), can I put the Bitmap in the picture box on my form?

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Ivan Prodanov
  • 34,634
  • 78
  • 176
  • 248

3 Answers3

61

Have you tried this?

pictureBox.Image = bmp;
ChrisF
  • 134,786
  • 31
  • 255
  • 325
8

I had some code resembling the accepted answer that caused a memory leak. Problem is that when you set the picture box image to the bitmap, you're still referring to the bitmap, rather than creating a copy. If you need to set the image multiple times you need to make sure you're disposing all the old bitmaps.

This is for anyone who's looking to clone a bitmap to an image box. Try this:

if (pictureBox.Image != null) pictureBox.Image.Dispose();
pictureBox.Image = myBitmap.Clone(
    new Rectangle(0, 0, myBitmap.Width, myBitmap.Height), 
    System.Drawing.Imaging.PixelFormat.DontCare);
JSideris
  • 5,101
  • 3
  • 32
  • 50
  • 1
    Thanks. Trying to use the bitmap without cloning it was throwing an exception in the System.Drawing.Dll. Using your .Clone suggestion fixed the issue for me! – saurabhj Mar 29 '16 at 06:54
0

If you are working with C++ programming language, it can be done like this:

void backGroundImage()
{
    Image^ back = gcnew Bitmap("C:\\Users\\User\\Documents\\image.bmp");
    pictureBox1->BackGroundImage = back;
};

Then you can call backGroundImage when you need to load a bitmap.

Maxwell175
  • 1,954
  • 1
  • 17
  • 27
r.mirzojonov
  • 1,209
  • 10
  • 18