读取/保存PixelFormat.Format48bppRgb PNG位图

本文关键字:PNG 位图 Format48bppRgb PixelFormat 保存 读取 | 更新日期: 2023-09-27 18:07:12

我已经能够创建一个Format48bppRgb .PNG文件(从一些内部HDR数据)使用以下c#代码:

Bitmap bmp16 = new Bitmap(_viewer.Width, _viewer.Height, System.Drawing.Imaging.PixelFormat.Format48bppRgb);
System.Drawing.Imaging.BitmapData data16 = bmp16.LockBits(_viewer.ClientRectangle, System.Drawing.Imaging.ImageLockMode.WriteOnly, bmp16.PixelFormat);
unsafe {  (populates bmp16) }
bmp16.Save( "C:/temp/48bpp.png", System.Drawing.Imaging.ImageFormat.Png );

ImageMagik(和其他应用程序)验证这确实是一个16bpp的图像:

C:'temp>identify 48bpp.png
48bpp.png PNG 1022x1125 1022x1125+0+0 DirectClass 16-bit 900.963kb

我很失望,然而,发现在读取PNG返回时,它已被转换为Format32bppRgb,使用:

Bitmap bmp = new Bitmap( "c:/temp/48bpp.png", false );
String info = String.Format("PixelFormat: {0}", bmp.PixelFormat );
...

鉴于PNG编解码器可以编写Format48bppRgb,是否有任何方法我可以使用。net在没有转换的情况下读取它?我不介意如果它这样做一个DrawImage调用,但我想访问一些直方图/图像处理工作的解压,原始数据。

读取/保存PixelFormat.Format48bppRgb PNG位图

供参考-我确实找到了一个。net解决方案,使用System.Windows.Media.Imaging(我一直严格使用WinForms/GDI+ -这需要添加WPF程序集,但工作)。这样,我得到一个Format64bppArgb PixelFormat,所以没有丢失的信息:

using System.Windows.Media.Imaging; // Add PresentationCore, WindowsBase, System.Xaml
...
    // Open a Stream and decode a PNG image
Stream imageStreamSource = new FileStream(fd.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
    // Convert WPF BitmapSource to GDI+ Bitmap
Bitmap bmp = _bitmapFromSource(bitmapSource);
String info = String.Format("PixelFormat: {0}", bmp.PixelFormat );
MessageBox.Show(info);

下面的代码片段来自:http://www.generoso.info/blog/wpf-system.drawing.bitmap-to-bitmapsource-and-viceversa.html

private System.Drawing.Bitmap _bitmapFromSource(BitmapSource bitmapsource) 
{ 
    System.Drawing.Bitmap bitmap; 
    using (MemoryStream outStream = new MemoryStream()) 
    { 
        // from System.Media.BitmapImage to System.Drawing.Bitmap 
        BitmapEncoder enc = new BmpBitmapEncoder(); 
        enc.Frames.Add(BitmapFrame.Create(bitmapsource)); 
        enc.Save(outStream); 
        bitmap = new System.Drawing.Bitmap(outStream); 
    } 
    return bitmap; 
} 

如果有人知道一种不需要WPF的方法,请分享!

使用Image.FromFile(String, Boolean)Bitmap.FromFile(String, Boolean)

并将布尔值设置为true。所有图像属性将保存在新图像中。

这里的字符串是文件名的完整路径…

如果图像已经加载到程序中,并且你想用它创建一个新的位图,你也可以使用

MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Bmp); // img is any Image, previously opened or came as a parameter
Bitmap bmp = (Bitmap)Bitmap.FromStream(ms,true);

常用的替代方法是

Bitmap bmp = new Bitmap(img); // this won't preserve img.PixelFormat