Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Bitmap PixelFormats in C#

Tags:

c#

.net

image

I need to convert a Bitmap from PixelFormat.Format32bppRgb to PixelFormat.Format32bppArgb.

I was hoping to use Bitmap.Clone, but it does not seem to be working.

Bitmap orig = new Bitmap("orig.bmp"); Bitmap clone = orig.Clone(new Rectangle(0,0,orig.Width,orig.Height), PixelFormat.Format24bppArgb); 

If I run the above code and then check clone.PixelFormat it is set to PixelFormat.Format32bppRgb. What is going on/how do I convert the format?

like image 977
Jono Avatar asked Jan 06 '10 21:01

Jono


2 Answers

Sloppy, not uncommon for GDI+. This fixes it:

Bitmap orig = new Bitmap(@"c:\temp\24bpp.bmp"); Bitmap clone = new Bitmap(orig.Width, orig.Height,     System.Drawing.Imaging.PixelFormat.Format32bppPArgb);  using (Graphics gr = Graphics.FromImage(clone)) {     gr.DrawImage(orig, new Rectangle(0, 0, clone.Width, clone.Height)); }  // Dispose orig as necessary... 
like image 156
Hans Passant Avatar answered Sep 25 '22 05:09

Hans Passant


For some reason if you create a Bitmap from a file path, i.e. Bitmap bmp = new Bitmap("myimage.jpg");, and call Clone() on it, the returned Bitmap will not be converted.

However if you create another Bitmap from your old Bitmap, Clone() will work as intended.

Try something like this:

using (Bitmap oldBmp = new Bitmap("myimage.jpg")) using (Bitmap newBmp = new Bitmap(oldBmp)) using (Bitmap targetBmp = newBmp.Clone(new Rectangle(0, 0, newBmp.Width, newBmp.Height), PixelFormat.Format32bppArgb)) {     // targetBmp is now in the desired format. } 
like image 36
Dan7 Avatar answered Sep 22 '22 05:09

Dan7