在 C# 中转换位图像素格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2016406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:41:58  来源:igfitidea点击:

Converting Bitmap PixelFormats in C#

c#.netimage

提问by Jono

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

我需要一个位图从转换PixelFormat.Format32bppRgbPixelFormat.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. What is going on/how do I convert the format?

如果我运行上面的代码然后检查 clone.PixelFormat 它被设置为PixelFormat.Format32bppRgb. 发生了什么/如何转换格式?

采纳答案by Hans Passant

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

马虎,GDI+ 并不少见。这修复了它:

Bitmap orig = new Bitmap(@"c:\tempbpp.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...

回答by Benjamin Podszun

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 gto define the interpolation mode for quality etc.

应该这样工作。也许你想设置一些参数g来定义质量等的插值模式。

回答by Dan7

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

出于某种原因,如果您Bitmap从文件路径创建 aBitmap bmp = new Bitmap("myimage.jpg");并调用Clone()它,则返回的Bitmap将不会被转换。

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

但是,如果您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.
}