Browse Source

add alpha pallette if any alpha channel set

af/merge-core
Scott Williams 9 years ago
parent
commit
a36be6c76a
  1. 36
      src/ImageSharp/Formats/Png/PngEncoderCore.cs

36
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<byte> transparentPixels = new List<byte>();
byte pixelCount = (byte)palette.Length;
// Get max colors for bit depth.
int colorTableLength = (int)Math.Pow(2, header.BitDepth) * 3;
byte[] colorTable = ArrayPool<byte>.Shared.Rent(colorTableLength);
byte[] alphaTable = ArrayPool<byte>.Shared.Rent(pixelCount);
byte[] bytes = ArrayPool<byte>.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;

Loading…
Cancel
Save