Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert the image in a PictureBox into a bitmap

I have used the following code to convert the image in a PictureBox into a Bitmap:

bmp = (Bitmap)pictureBox2.Image;

But I am getting the result as bmp = null. Can anyone tell me how I do this?

like image 697
DjMalaikallan Avatar asked May 18 '12 11:05

DjMalaikallan


3 Answers

As per my understanding your have not assigned PictureBox's Image property, so that it is returning null on type cast.

PictureBox property automatically convert the Image format and if you see the tooltip on Image property, it will Show System.Drawing.Bitmap. Check your image property is correctly assigned.

Check this, it is working at my side.

private void button1_Click(object sender, EventArgs e)
{
    var bmp = (Bitmap)pictureBox1.Image;
}

private void TestForm12_Load(object sender, EventArgs e)
{
    pictureBox1.Image = Image.FromFile("c:\\url.gif");
}

/// Using BitMap Class

 Bitmap bmp = new Bitmap(pictureBox2.Image);

You can directly cast pictureBox2.Image to Bitmap as you are doing and also using the Bitmap class to convert to Bitmap class object.

Ref: Bitmap Constructor (Image).

You can find more options here with the Bitmap Class

like image 181
Niranjan Singh Avatar answered Oct 21 '22 07:10

Niranjan Singh


Bitmap bitmap = new Bitmap(pictureBox2.Image)

http://msdn.microsoft.com/en-us/library/ts25csc8.aspx

like image 7
Tilak Avatar answered Oct 21 '22 06:10

Tilak


I think you looking for this:

Bitmap bmp = new Bitmap(pictureBox2.Image)
like image 3
Renatas M. Avatar answered Oct 21 '22 07:10

Renatas M.