Convert the image in a PictureBox into a bitmap
Solution 1
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
Solution 2
Bitmap bitmap = new Bitmap(pictureBox2.Image)
http://msdn.microsoft.com/en-us/library/ts25csc8.aspx
Solution 3
I think you looking for this:
Bitmap bmp = new Bitmap(pictureBox2.Image)
DjMalaikallan
I am learning by doing .Net programmer . Interested in Windows Application and Enterprise application Development . I know English , Tamil , Hindi , Malayalam and Telugu Languages . My hobbies are surfing and roaming .
Updated on August 06, 2020Comments
-
DjMalaikallan almost 4 years
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? -
DjMalaikallan about 12 yearsHi Tilak , I just applied the code but it gives me an error as "Object Reference not set to an instance of an Object"
-
Tilak about 12 yearshave you checked pictureBox2.Image for null
-
Nyerguds almost 6 yearsYou should never use
Image.FromFile(path)
. It is a simple wrapper around theNew Bitmap(path)
constructor which has no extra advantages at all but loses the more specificBitmap
type in the process. So just use theNew Bitmap(path)
constructor instead. Usingnew Bitmap(image)
on the result is also not advised since it converts the image to 32bpp ARGB, which might not be desired if you're working specific image types you want to preserve on later saves or manipulations (like 24bpp RGB, or indexed images with palettes).