Jono
Jono

Reputation: 1750

Converting Bitmap PixelFormats in C#

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?

Upvotes: 61

Views: 89984

Answers (3)

Hans Passant
Hans Passant

Reputation: 941465

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...

Upvotes: 109

Dan7
Dan7

Reputation: 1727

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.
}

Upvotes: 40

Benjamin Podszun
Benjamin Podszun

Reputation: 9827

using (var bmp = new Bitmap(width, height, PixelFormat.Format24bppArgb))
using (var g = Graphics.FromImage(bmp)) {
  g.DrawImage(..);
}

Should work like that. Maybe you want to set some parameters on g to define the interpolation mode for quality etc.

Upvotes: 8

Related Questions