From a36be6c76a2dc69c66d40f3937ec263fd39c06ab Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Mon, 10 Apr 2017 16:28:39 +0100 Subject: [PATCH] add alpha pallette if any alpha channel set --- src/ImageSharp/Formats/Png/PngEncoderCore.cs | 36 +++++++++----------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/ImageSharp/Formats/Png/PngEncoderCore.cs b/src/ImageSharp/Formats/Png/PngEncoderCore.cs index 552673179..1e2203e36 100644 --- a/src/ImageSharp/Formats/Png/PngEncoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngEncoderCore.cs @@ -495,35 +495,31 @@ namespace ImageSharp.Formats // Grab the palette and write it to the stream. TColor[] palette = quantized.Palette; - int pixelCount = palette.Length; - List transparentPixels = new List(); + byte pixelCount = (byte)palette.Length; // Get max colors for bit depth. int colorTableLength = (int)Math.Pow(2, header.BitDepth) * 3; byte[] colorTable = ArrayPool.Shared.Rent(colorTableLength); + byte[] alphaTable = ArrayPool.Shared.Rent(pixelCount); byte[] bytes = ArrayPool.Shared.Rent(4); - + bool anyAlpha = false; try { - for (int i = 0; i < pixelCount; i++) + for (byte i = 0; i < pixelCount; i++) { - int offset = i * 3; - palette[i].ToXyzwBytes(bytes, 0); + if (quantized.Pixels.Contains(i)) + { + int offset = i * 3; + palette[i].ToXyzwBytes(bytes, 0); - int alpha = bytes[3]; + byte alpha = bytes[3]; - colorTable[offset] = bytes[0]; - colorTable[offset + 1] = bytes[1]; - colorTable[offset + 2] = bytes[2]; + colorTable[offset] = bytes[0]; + colorTable[offset + 1] = bytes[1]; + colorTable[offset + 2] = bytes[2]; - if (alpha < 255 && alpha <= this.options.Threshold) - { - // Ensure the index is actually being used in our array. - // I'd like to find a faster way of doing this. - if (quantized.Pixels.Contains((byte)i)) - { - transparentPixels.Add((byte)i); - } + anyAlpha = anyAlpha || alpha < 255; + alphaTable[i] = alpha; } } @@ -536,9 +532,9 @@ namespace ImageSharp.Formats } // Write the transparency data - if (transparentPixels.Any()) + if (anyAlpha) { - this.WriteChunk(stream, PngChunkTypes.PaletteAlpha, transparentPixels.ToArray()); + this.WriteChunk(stream, PngChunkTypes.PaletteAlpha, alphaTable, 0, pixelCount); } return quantized;