在C#中转换位图PixelFormats

Jon*_*ono 46 .net c# image

我需要将Bitmap转换PixelFormat.Format32bppRgbPixelFormat.Format32bppArgb.

我希望使用Bitmap.Clone,但似乎没有用.

Bitmap orig = new Bitmap("orig.bmp");
Bitmap clone = orig.Clone(new Rectangle(0,0,orig.Width,orig.Height), PixelFormat.Format24bppArgb);
Run Code Online (Sandbox Code Playgroud)

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

Han*_*ant 81

邋,, GDI +并不少见.这解决了它:

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...
Run Code Online (Sandbox Code Playgroud)


Dan*_*an7 32

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

但是,如果您Bitmap从旧的创建另一个Bitmap,Clone()将按预期工作.

尝试这样的事情:

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.
}
Run Code Online (Sandbox Code Playgroud)

  • +1感谢Dan7解释触发器的内容.我之前见过`新的Bitmap(新的Bitmap("image.jpg"))`但不知道为什么会有效. (5认同)

Ben*_*zun 7

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

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