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