png中的透明度通过在标题中添加可选的“tRNS”块来指定每个调色板条目的alpha值。 .Net类正确地读取和应用这个,所以我不明白他们为什么坚持把图像转换为32位。更重要的是,当存在透明度块时,即使它将所有颜色标记为完全不透明,也会发生错误总是。
png格式的结构相当简单;在识别字节之后,每个块是内容大小的4个字节,然后是块ID的4个ASCII字符,然后是块内容本身,最后是4个字节的块CRC值。
鉴于这种结构,该解决方案是相当简单:
- 文件读入到一个字节数组。
- 通过分析标头确保它是一个调色板的png文件。
- 通过从块标题跳转到块标题来查找“tRNS”块。
- 从块中读取alpha值。
- 创建一个包含图像数据的新字节数组,但切割了“tRNS”块。
- 使用从调整后的字节数据创建的
MemoryStream
创建Bitmap
对象,从而生成正确的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 BitmapLoader
{
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 can be found at http://www.libpng.org/pub/png/book/chapter08.html
/// </summary>
/// <param name="filename">Filename to load</param>
/// <returns>The loaded image</returns>
public static Bitmap LoadBitmap(String filename)
{
Byte[] data = File.ReadAllBytes(filename);
return LoadBitmap(data);
}
/// <summary>
/// Loads an image, checks if it is a PNG containing palette transparency, and if so, ensures it loads correctly.
/// The theory 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;
}
}
}
}
Bitmap loadedImage;
using (MemoryStream ms = new MemoryStream(data))
using (Bitmap tmp = new Bitmap(ms))
loadedImage = ImageUtils.CloneImage(tmp);
ColorPalette pal = loadedImage.Palette;
if (pal.Entries.Length == 0 || transparencyData == null)
return loadedImage;
for (Int32 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;
return loadedImage;
}
/// <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 (chunkName.Length != 4)
throw new ArgumentException("Chunk must be 4 characters!", "chunkName");
Byte[] chunkNamebytes = Encoding.ASCII.GetBytes(chunkName);
if (chunkNamebytes.Length != 4)
throw new ArgumentException("Chunk must be 4 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);
// Alternative for more visual debugging:
//String currentChunk = Encoding.ASCII.GetString(testBytes);
//if (chunkName.Equals(currentChunk))
// return offset;
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;
}
}
所提ImageUtils.CloneImage
是,据我所知,加载位图和从任何后备资源,如文件或流取消链接它的只有100%安全的方式。 It can be found here.
您的代码不显示如何阅读图像。 –
问题是“Screen-SaverBouncing.png”是一个8位图像(从Windows 7的属性窗口中可以看到),但colorPalette.Entries.Length始终为零。另外,如果我在IrfanViewer中打开这个图像,我可以看到调色板,修改它并保存。如果我在这个新保存的文件上运行上面的代码,那么colorPalette.Entries.Length是256。 –
现在解决了这个问题,因为问题出在png图片上,而不是代码上。 –