2011-01-13 96 views
3

我需要处理和保存图像的原始bpp(1 - BnW,8 - 灰色,24色)。 处理后,我总是有24bpp(由于与Aforge.Net处理)。我通过原BPP节约功能,我使用下面的代码保存:C#为什么Bitmap.Save忽略位图的PixelFormat?

private static Bitmap changePixelFormat(Bitmap input, PixelFormat format) 
    { 
     Bitmap retval = new Bitmap(input.Width, input.Height, format); 
     retval.SetResolution(input.HorizontalResolution, input.VerticalResolution); 
     Graphics g = Graphics.FromImage(retval); 
     g.DrawImage(input, 0, 0); 
     g.Dispose(); 
     return retval; 
    } 

当我通过:

PixelFormat.Format8bppIndexed 

我发现了异常:“图形对象不能创建

Graphics g = Graphics.FromImage(retval); 

我已经尝试了下面的代码:

Bitmap s = new Bitmap("gray.jpg"); 
     Bitmap NewPicture = s.Clone(new Rectangle(0, 0, s.Width, s.Height),     PixelFormat.Format8bppIndexed); 
在行索引的像素格式”形象

这个 “NewImage” 之后的PixelFormat 8bppIndexed,但是当我节省NewImage:

NewPicture.Save("hello.jpg", ImageFormat.Jpeg); 

hello.jpg有24 bpp的。

我需要保持原始图像的bpp和图像格式。

为什么Bitmap.Save忽略位图的PixelFormat?

============================================== =========

谢谢你们,我已经找到了解决办法: http://freeimage.sourceforge.net/license.html

有了这个免费的图书馆,可以保存图像(JPEG特)到灰阶8位的帮助。

+0

那么,什么是问题?为什么`Bitmap.Save`忽略正在保存的图像的`PixelFormat`?或者我该如何解决带有索引像素格式的`Graphics.FromImage`引发的异常? – 2011-01-13 12:13:18

+0

对不起,我还没有添加任何问题。问题是:“为什么Bitmap.Save忽略位图的PixelFormat?” – ieaglle 2011-01-13 12:17:03

回答

4

这是将位图转换为1bpp/8bpp位图的代码。 1bpp/8bpp in C#.

在您的changePixelFormat方法中,您可以检查它需要转换为什么格式,然后如果是1bpp或8 bpp,那么使用链接代码和所有其他格式的代码。

Graphics.FromImagedocumentation有备注:

如果图像具有索引像素 格式,此方法将引发 例外用,“A 图形对象不能从 创建具有的图像的消息索引像素 格式“。索引的像素格式为 ,如下表所示。

Format1bppIndexed

Format4bppIndexed

Format8bppIndexed

新零件:

这是我短暂谷歌上搜索后发现:

8bpp的gdiplus版本 1.0不支持灰度图像和8bpp jpg。在Windows 7中有一个新版本的gdiplus,支持灰度 图像和更多增强的编解码器支持。

支持8bpp索引的jpeg图像 Microsoft的WIC API。

您可以尝试从微软的 下载站点下载WIC浏览器。

GDI+ 8 bit load/save bug

标准JPEG仅支持24位图像。

5

我几乎肯定JPEG图像格式不支持索引图像。因此,即使您创建了指定PixelFormat.Format8bppIndexed的图像,当您试图将其保存为JPEG格式时,GDI +也会将其转换为其他格式。在这种情况下,你已经确定这是24 bpp。

相反,您需要将图像保存为BMP或GIF。例如:

NewPicture.Save("hello.jpg", ImageFormat.Bmp); 

请参阅支持索引颜色的图像文件格式表here on Wikipedia

0

如果你正在寻找一个真正的8位灰度位图图像,那么我做了一个关于它的detailed StackOverflow post。它可以在任何操作系统(Windows/Mac/Linux)上运行,而不仅仅是Windows 7.我希望它有帮助。

0

对非索引图像使用Graphics类。 处理索引图像时UseBitmap.LockBits和Bitmap.UnlockBits