Converting Bitmap PixelFormats in C#

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

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

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.

Tags:

C#

.Net

Image