namespace SixLabors.ImageSharp.Tests { using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Quantization; using Xunit; public class QuantizedImageTests { [Fact] public void QuantizersDitherByDefault() { var palette = new PaletteQuantizer(); var octree = new OctreeQuantizer(); var wu = new WuQuantizer(); Assert.True(palette.Dither); Assert.True(octree.Dither); Assert.True(wu.Dither); } [Theory] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32, true)] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32, false)] public void PaletteQuantizerYieldsCorrectTransparentPixel(TestImageProvider provider, bool dither) where TPixel : struct, IPixel { using (Image image = provider.GetImage()) { Assert.True(image[0, 0].Equals(default(TPixel))); IQuantizer quantizer = new PaletteQuantizer { Dither = dither }; foreach (ImageFrame frame in image.Frames) { QuantizedFrame quantized = quantizer.Quantize(frame, 256); int index = this.GetTransparentIndex(quantized); Assert.Equal(index, quantized.Pixels[0]); } } } [Theory] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32, true)] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32, false)] public void OctreeQuantizerYieldsCorrectTransparentPixel(TestImageProvider provider, bool dither) where TPixel : struct, IPixel { using (Image image = provider.GetImage()) { Assert.True(image[0, 0].Equals(default(TPixel))); IQuantizer quantizer = new OctreeQuantizer { Dither = dither }; foreach (ImageFrame frame in image.Frames) { QuantizedFrame quantized = quantizer.Quantize(frame, 256); int index = this.GetTransparentIndex(quantized); Assert.Equal(index, quantized.Pixels[0]); } } } [Theory] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32, true)] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32, false)] public void WuQuantizerYieldsCorrectTransparentPixel(TestImageProvider provider, bool dither) where TPixel : struct, IPixel { using (Image image = provider.GetImage()) { Assert.True(image[0, 0].Equals(default(TPixel))); IQuantizer quantizer = new WuQuantizer() { Dither = dither }; foreach (ImageFrame frame in image.Frames) { QuantizedFrame quantized = quantizer.Quantize(frame, 256); int index = this.GetTransparentIndex(quantized); Assert.Equal(index, quantized.Pixels[0]); } } } private int GetTransparentIndex(QuantizedFrame quantized) where TPixel : struct, IPixel { // Transparent pixels are much more likely to be found at the end of a palette int index = -1; var trans = default(Rgba32); for (int i = quantized.Palette.Length - 1; i >= 0; i--) { quantized.Palette[i].ToRgba32(ref trans); if (trans.Equals(default(Rgba32))) { index = i; } } return index; } } }