[英]Converting Bitmap PixelFormats in C#
I need to convert a Bitmap from PixelFormat.Format32bppRgb
to PixelFormat.Format32bppArgb
. 我需要将位图从
PixelFormat.Format32bppRgb
转换为PixelFormat.Format32bppArgb
。
I was hoping to use Bitmap.Clone, but it does not seem to be working. 我希望使用Bitmap.Clone,但似乎无法正常工作。
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
. 如果我运行上面的代码,然后检查clone.PixelFormat,它将设置为
PixelFormat.Format32bppRgb
。 What is going on/how do I convert the format? 怎么回事/如何转换格式?
Sloppy, not uncommon for GDI+. 马虎,对于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, ie Bitmap bmp = new Bitmap("myimage.jpg");
由于某种原因,如果您从文件路径创建
Bitmap
,即位Bitmap bmp = new Bitmap("myimage.jpg");
, and call Clone()
on it, the returned Bitmap
will not be converted. ,然后对其调用
Clone()
,则将不会转换返回的Bitmap
。
However if you create another Bitmap
from your old Bitmap
, Clone()
will work as intended. 但是,如果您从旧的
Bitmap
创建另一个Bitmap
Bitmap
,则Clone()
将按预期工作。
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. 也许您想在
g
上设置一些参数以定义质量等插值模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.