C# - 正确加载索引的彩色图像文件

时间:2017-06-29 22:06:14

标签: c# image bitmap

所以我创建了一个索引颜色,每像素8位PNG(如果格式正确,我已经使用ImageMagick检查过)并且我想将它从磁盘加载到System.Drawing.Bitmap,同时保持8bpp像素格式,以查看(和操纵)其调色板。但是,如果我创建这样的位图:

Bitmap bitmap = new Bitmap("indexed-image.png");

生成的Bitmap会自动转换为32bpp图像格式,而bitmap.Palette.Entries字段则显示为空。

回答问题"如何在C#中将32bpp图像转换为8bpp?" StackOverflow上说这可能是将其转换回8bpp的有效方法:

bitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), PixelFormat.Format8bppIndexed);

然而,这会产生不正确的结果,因为调色板中的某些颜色是完全错误的。

如何将图像本机加载到8bpp,或者至少正确地将32bpp图像加载到8bpp?

2 个答案:

答案 0 :(得分:1)

我也有这个问题,似乎任何包含透明度的调色板png图像都无法加载为.Net框架调整,尽管.Net功能完全可以这样的文件。相反,如果文件是gif格式,或者调色板的png具有 no 透明度,则它没有问题。

调色板png中的透明度通过在标题中添加可选的“tRNS”块来工作,以指定每个调色板条目的alpha。 .Net类正确读取并应用它,所以我真的不明白为什么然后他们坚持将图像转换为32位。

png格式的结构相当简单;在识别字节之后,每个块是内容大小的4个字节(big-endian),然后是块id的4个ASCII字符,然后是块内容本身,最后是4个字节的块CRC值(再次,保存为大-endian)。

鉴于这种结构,解决方案非常简单:

  • 将文件读入字节数组。
  • 通过分析标题确保它是一个调色板的png文件。
  • 通过从块头跳转到块头来找到“tRNS”块。
  • 从块中读取alpha值。
  • 创建一个包含图像数据的新字节数组,但切出“tRNS”块。
  • 使用从调整后的字节数据创建的Bitmap创建MemoryStream对象,从而生成正确的8位图像。
  • 使用提取的Alpha数据修复调色板。

如果您执行检查和后退,您可以使用此功能加载任何图像,如果它恰好标识为具有透明度信息的调色板png,它将执行修复。

/// <summary>
/// Image loading toolset class which corrects the bug that prevents paletted PNG images with transparency from being loaded as paletted.
/// </summary>
public class BitmapHandler
{

    private static Byte[] PNG_IDENTIFIER = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};

    /// <summary>
    /// Loads an image, checks if it is a PNG containing palette transparency, and if so, ensures it loads correctly.
    /// The theory on the png internals can be found at http://www.libpng.org/pub/png/book/chapter08.html
    /// </summary>
    /// <param name="data">File data to load.</param>
    /// <returns>The loaded image.</returns>
    public static Bitmap LoadBitmap(Byte[] data)
    {
        Byte[] transparencyData = null;
        if (data.Length > PNG_IDENTIFIER.Length)
        {
            // Check if the image is a PNG.
            Byte[] compareData = new Byte[PNG_IDENTIFIER.Length];
            Array.Copy(data, compareData, PNG_IDENTIFIER.Length);
            if (PNG_IDENTIFIER.SequenceEqual(compareData))
            {
                // Check if it contains a palette.
                // I'm sure it can be looked up in the header somehow, but meh.
                Int32 plteOffset = FindChunk(data, "PLTE");
                if (plteOffset != -1)
                {
                    // Check if it contains a palette transparency chunk.
                    Int32 trnsOffset = FindChunk(data, "tRNS");
                    if (trnsOffset != -1)
                    {
                        // Get chunk
                        Int32 trnsLength = GetChunkDataLength(data, trnsOffset);
                        transparencyData = new Byte[trnsLength];
                        Array.Copy(data, trnsOffset + 8, transparencyData, 0, trnsLength);
                        // filter out the palette alpha chunk, make new data array
                        Byte[] data2 = new Byte[data.Length - (trnsLength + 12)];
                        Array.Copy(data, 0, data2, 0, trnsOffset);
                        Int32 trnsEnd = trnsOffset + trnsLength + 12;
                        Array.Copy(data, trnsEnd, data2, trnsOffset, data.Length - trnsEnd);
                        data = data2;
                    }
                }
            }
        }
        using(MemoryStream ms = new MemoryStream(data))
        using(Bitmap loadedImage = new Bitmap(ms))
        {
            if (loadedImage.Palette.Entries.Length != 0 && transparencyData != null)
            {
                ColorPalette pal = loadedImage.Palette;
                for (int i = 0; i < pal.Entries.Length; i++)
                {
                    if (i >= transparencyData.Length)
                        break;
                    Color col = pal.Entries[i];
                    pal.Entries[i] = Color.FromArgb(transparencyData[i], col.R, col.G, col.B);
                }
                loadedImage.Palette = pal;
            }
            // Images in .Net often cause odd crashes when their backing resource disappears.
            // This prevents that from happening by copying its inner contents into a new Bitmap object.
            return CloneImage(loadedImage, null);
        }
    }

    /// <summary>
    /// Finds the start of a png chunk. This assumes the image is already identified as PNG.
    /// It does not go over the first 8 bytes, but starts at the start of the header chunk.
    /// </summary>
    /// <param name="data">The bytes of the png image.</param>
    /// <param name="chunkName">The name of the chunk to find.</param>
    /// <returns>The index of the start of the png chunk, or -1 if the chunk was not found.</returns>
    private static Int32 FindChunk(Byte[] data, String chunkName)
    {
        if (data == null)
            throw new ArgumentNullException("data", "No data given!");
        if (chunkName == null)
            throw new ArgumentNullException("chunkName", "No chunk name given!");
        // Using UTF-8 as extra check to make sure the name does not contain > 127 values.
        Byte[] chunkNamebytes = Encoding.UTF8.GetBytes(chunkName);
        if (chunkName.Length != 4 || chunkNamebytes.Length != 4)
            throw new ArgumentException("Chunk name must be 4 ASCII characters!", "chunkName");
        Int32 offset = PNG_IDENTIFIER.Length;
        Int32 end = data.Length;
        Byte[] testBytes = new Byte[4];
        // continue until either the end is reached, or there is not enough space behind it for reading a new header
        while (offset < end && offset + 8 < end)
        {
            Array.Copy(data, offset + 4, testBytes, 0, 4);
            if (chunkNamebytes.SequenceEqual(testBytes))
                return offset;
            Int32 chunkLength = GetChunkDataLength(data, offset);
            // chunk size + chunk header + chunk checksum = 12 bytes.
            offset += 12 + chunkLength;
        }
        return -1;
    }

    private static Int32 GetChunkDataLength(Byte[] data, Int32 offset)
    {
        if (offset + 4 > data.Length)
            throw new IndexOutOfRangeException("Bad chunk size in png image.");
        // Don't want to use BitConverter; then you have to check platform endianness and all that mess.
        Int32 length = data[offset + 3] + (data[offset + 2] << 8) + (data[offset + 1] << 16) + (data[offset] << 24);
        if (length < 0)
            throw new IndexOutOfRangeException("Bad chunk size in png image.");
        return length;
    }

    /// <summary>
    /// Clones an image object to free it from any backing resources.
    /// Code taken from http://stackoverflow.com/a/3661892/ with some extra fixes.
    /// </summary>
    /// <param name="sourceImage">The image to clone.</param>
    /// <returns>The cloned image.</returns>
    public static Bitmap CloneImage(Bitmap sourceImage)
    {
        Rectangle rect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
        Bitmap targetImage = new Bitmap(rect.Width, rect.Height, sourceImage.PixelFormat);
        targetImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
        BitmapData sourceData = sourceImage.LockBits(rect, ImageLockMode.ReadOnly, sourceImage.PixelFormat);
        BitmapData targetData = targetImage.LockBits(rect, ImageLockMode.WriteOnly, targetImage.PixelFormat);
        Int32 actualDataWidth = ((Image.GetPixelFormatSize(sourceImage.PixelFormat) * rect.Width) + 7) / 8;
        Int32 h = sourceImage.Height;
        Int32 origStride = sourceData.Stride;
        Int32 targetStride = targetData.Stride;
        Byte[] imageData = new Byte[actualDataWidth];
        IntPtr sourcePos = sourceData.Scan0;
        IntPtr destPos = targetData.Scan0;
        // Copy line by line, skipping by stride but copying actual data width
        for (Int32 y = 0; y < h; y++)
        {
            Marshal.Copy(sourcePos, imageData, 0, actualDataWidth);
            Marshal.Copy(imageData, 0, destPos, actualDataWidth);
            sourcePos = new IntPtr(sourcePos.ToInt64() + origStride);
            destPos = new IntPtr(destPos.ToInt64() + targetStride);
        }
        targetImage.UnlockBits(targetData);
        sourceImage.UnlockBits(sourceData);
        // For indexed images, restore the palette. This is not linking to a referenced
        // object in the original image; the getter of Palette creates a new object when called.
        if ((sourceImage.PixelFormat & PixelFormat.Indexed) != 0)
            targetImage.Palette = sourceImage.Palette;
        // Restore DPI settings
        targetImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
        return targetImage;
    }

}

但是这个方法似乎只解决了8位和4位png的问题。由Gimp重新保存的只有4种颜色的png变为2位png,尽管不包含任何透明度,仍然以32位颜色打开。

实际上存在类似的问题,即保存调色板大小; .Net框架可以完美地处理加载png文件,其调色板不是完整大小(8位小于256,4位小于16),但保存文件时,它会将其填充到完整的调色板。这可以通过类似的方式修复by post-processing the chunks after saving to a MemoryStream。但这需要计算CRC。

另请注意,虽然这应该可以加载任何图像类型,但它无法在动画GIF文件上正常工作,因为最后使用的CloneImage函数只能复制单个图像。

答案 1 :(得分:0)

据我所知,默认的8bpp调色板不会作为PNG的索引图像加载。您可以修复文件中的调色板,或将文件转换为GIF,BMP或TIFF。

修复调色板代码:

ColorPalette pal;
pal = bmp.Palette;
for (int i = 16; i < 40; i++)
    pal.Entries[i] = Color.FromArgb(i, i, i);
bmp.Palette = pal;