6

好的,我有一个来自外部应用程序的 8 位索引格式的图像。我需要将此图像转换为完全相同大小的 24 位格式。

我尝试创建一个大小相同且类型为 Format24bppRgb 的新位图,然后使用 Graphics 对象在其上绘制 8 位图像,然后将其保存为 Bmp。这种方法不会出错,但是当我打开生成的图像时,BMP 标头具有各种时髦的值。高度和宽度是巨大的,此外,压缩标志和其他一些标志有有趣的(和大的)值。不幸的是,我的特殊要求是将此文件传递给特定的打印机驱动程序,该驱动程序需要具有特定标题值的 24 位图像(我试图通过 GDI+ 实现)

有人知道将索引文件“上转换”为未索引的 24 位文件的示例吗?如果不是一个例子,我应该从哪条路径开始编写自己的?

-Kevin Grossnicklaus kvgros@sseinc.com

4

4 回答 4

11

我使用下面的代码将图像从 8bpp“上转换”为 24bpp。使用十六进制编辑器检查生成的 24bpp 文件并与 8bpp 文件进行比较显示两个文件的高度和宽度没有差异。也就是说,8bpp 的图像是 1600x1200,24bpp 的图像具有相同的值。

    private static void ConvertTo24(string inputFileName, string outputFileName)
    {
        Bitmap bmpIn = (Bitmap)Bitmap.FromFile(inputFileName);

        Bitmap converted = new Bitmap(bmpIn.Width, bmpIn.Height, PixelFormat.Format24bppRgb);
        using (Graphics g = Graphics.FromImage(converted))
        {
            // Prevent DPI conversion
            g.PageUnit = GraphicsUnit.Pixel
            // Draw the image
            g.DrawImageUnscaled(bmpIn, 0, 0);
        }
        converted.Save(outputFileName, ImageFormat.Bmp);
    }

标题中的其他所有内容看起来都很合理,并且图像在我的系统上显示相同。你看到了什么“时髦的价值观”?

于 2009-03-23T03:46:17.850 回答
4

这是我的转换代码。注意源图像和结果图像之间的分辨率匹配。

    private void ConvertTo24bppPNG(Stream imageDataAsStream, out byte[] data)
    {
        using ( Image img = Image.FromStream(imageDataAsStream) )
        {
            using ( Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb) )
            {
                // ensure resulting image has same resolution as source image
                // otherwise resulting image will appear scaled
                bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);

                using ( Graphics gfx = Graphics.FromImage(bmp) )
                {
                    gfx.DrawImage(img, 0, 0);
                }

                using ( MemoryStream ms = new MemoryStream() )
                {
                    bmp.Save(ms, ImageFormat.Png);
                    data = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(data, 0, (int) ms.Length);
                }
            }
        }
    }
于 2011-06-07T22:36:08.480 回答
0

您创建的位图与输入的宽度和高度相同,但生成的 BMP 更大,这似乎很奇怪。你能发布一些代码吗?

于 2009-03-23T02:39:14.750 回答
0

问题可能是源图像和输出图像的 Vertical- 和 Horizo​​ntalResolution 之间的差异。如果您加载分辨率为 72 DPI 的 8bpp 索引位图,然后创建一个新的 24bpp 位图(默认分辨率将为 96 DPI ......至少在我的系统上),然后使用 Graphics.DrawImage 到新的位图,您的图像将显示为略微放大和裁剪。

话虽如此,我不知道如何正确创建输出位图和/或图形对象以在保存时正确缩放。我怀疑这与使用英寸而不是像素等通用比例创建图像有关。

于 2009-03-23T03:35:34.130 回答