C#为什么Bitmap.Save会忽略Bitmap的PixelFormat?

iea*_*lle 4 c# bitmap image-processing pixelformat

我需要处理和保存原始bpp中的图像(1 - 对于BnW,8 - 对于灰色,24 - 颜色).处理后我总是有24bpp(由于使用Aforge.Net处理).我将原始bpp传递给保存功能,我正在使用下一个代码进行保存:

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

当我通过时:

PixelFormat.Format8bppIndexed
Run Code Online (Sandbox Code Playgroud)

我得到一个例外:"图形对象无法在索引像素格式中创建图像":

Graphics g = Graphics.FromImage(retval);
Run Code Online (Sandbox Code Playgroud)

我已经尝试了下一个代码:

Bitmap s = new Bitmap("gray.jpg");
        Bitmap NewPicture = s.Clone(new Rectangle(0, 0, s.Width, s.Height),                   PixelFormat.Format8bppIndexed);
Run Code Online (Sandbox Code Playgroud)

在此"NewImage"之后有PixelFormat 8bppIndexed,但是当我保存NewImage时:

NewPicture.Save("hello.jpg", ImageFormat.Jpeg);
Run Code Online (Sandbox Code Playgroud)

hello.jpg有24bpp.

我需要保留原始图像的bpp和图像格式.

为什么Bitmap.Save会忽略Bitmap的PixelFormat?

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

谢谢大家,我找到了一个解决方案:http: //freeimage.sourceforge.net/license.html

借助这个免费库,可以将图像(尤其是JPEG)保存到8位灰度级.

Cod*_*ray 5

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

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

NewPicture.Save("hello.jpg", ImageFormat.Bmp);
Run Code Online (Sandbox Code Playgroud)

请参阅维基百科上的支持索引颜色的图像文件格式表.