Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 9 additions & 18 deletions src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -671,12 +671,9 @@ private void Write4BitPixelData<TPixel>(
CancellationToken cancellationToken)
where TPixel : unmanaged, IPixel<TPixel>
{
using IQuantizer<TPixel> frameQuantizer = this.quantizer.CreatePixelSpecificQuantizer<TPixel>(configuration, new QuantizerOptions
{
MaxColors = 16,
Dither = this.quantizer.Options.Dither,
DitherScale = this.quantizer.Options.DitherScale
});
using IQuantizer<TPixel> frameQuantizer = this.quantizer.CreatePixelSpecificQuantizer<TPixel>(
configuration,
this.quantizer.Options.DeepClone(o => o.MaxColors = 16));

frameQuantizer.BuildPalette(this.pixelSamplingStrategy, encodingFrame);

Expand Down Expand Up @@ -728,12 +725,9 @@ private void Write2BitPixelData<TPixel>(
CancellationToken cancellationToken)
where TPixel : unmanaged, IPixel<TPixel>
{
using IQuantizer<TPixel> frameQuantizer = this.quantizer.CreatePixelSpecificQuantizer<TPixel>(configuration, new QuantizerOptions
{
MaxColors = 4,
Dither = this.quantizer.Options.Dither,
DitherScale = this.quantizer.Options.DitherScale
});
using IQuantizer<TPixel> frameQuantizer = this.quantizer.CreatePixelSpecificQuantizer<TPixel>(
configuration,
this.quantizer.Options.DeepClone(o => o.MaxColors = 4));

frameQuantizer.BuildPalette(this.pixelSamplingStrategy, encodingFrame);

Expand Down Expand Up @@ -794,12 +788,9 @@ private void Write1BitPixelData<TPixel>(
CancellationToken cancellationToken)
where TPixel : unmanaged, IPixel<TPixel>
{
using IQuantizer<TPixel> frameQuantizer = this.quantizer.CreatePixelSpecificQuantizer<TPixel>(configuration, new QuantizerOptions
{
MaxColors = 2,
Dither = this.quantizer.Options.Dither,
DitherScale = this.quantizer.Options.DitherScale
});
using IQuantizer<TPixel> frameQuantizer = this.quantizer.CreatePixelSpecificQuantizer<TPixel>(
configuration,
this.quantizer.Options.DeepClone(o => o.MaxColors = 2));

frameQuantizer.BuildPalette(this.pixelSamplingStrategy, encodingFrame);

Expand Down
19 changes: 12 additions & 7 deletions src/ImageSharp/Formats/Gif/GifEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,15 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
int ti = GetTransparentIndex(quantized, frameMetadata);
if (ti >= 0 || gifMetadata.GlobalColorTable.Value.Length < 256)
{
// We avoid dithering by default to preserve the original colors.
globalQuantizer = new PaletteQuantizer(
gifMetadata.GlobalColorTable.Value,
options.DeepClone(o => o.Dither = null),
ti,
Color.Transparent);
// We avoid dithering and match colors exactly to preserve the original colors. The first frame
// quantizes with these options too, so they replace the default options.
options = options.DeepClone(o =>
{
o.Dither = null;
o.ColorMatchingMode = ColorMatchingMode.Exact;
});

globalQuantizer = new PaletteQuantizer(gifMetadata.GlobalColorTable.Value, options, ti, Color.Transparent);
}
else
{
Expand Down Expand Up @@ -418,7 +421,7 @@ private IndexedImageFrame<TPixel> QuantizeFrameAndUpdateMetadata<TPixel>(
if (metadata.LocalColorTable?.Length > 0)
{
// We can use the color data from the decoded metadata here.
// We avoid dithering by default to preserve the original colors.
// We avoid dithering and match colors exactly to preserve the original colors.
ReadOnlyMemory<Color> palette = metadata.LocalColorTable.Value;
if (requiresTransparency && !metadata.HasTransparency)
{
Expand All @@ -438,6 +441,7 @@ private IndexedImageFrame<TPixel> QuantizeFrameAndUpdateMetadata<TPixel>(
{
o.MaxColors = palette.Length;
o.Dither = null;
o.ColorMatchingMode = ColorMatchingMode.Exact;
});
PaletteQuantizer quantizer = new(palette, options, transparencyIndex, transparentColor);
using IQuantizer<TPixel> frameQuantizer = quantizer.CreatePixelSpecificQuantizer<TPixel>(this.configuration);
Expand All @@ -462,6 +466,7 @@ private IndexedImageFrame<TPixel> QuantizeFrameAndUpdateMetadata<TPixel>(
{
o.MaxColors = palette.Length;
o.Dither = null;
o.ColorMatchingMode = ColorMatchingMode.Exact;
});
PaletteQuantizer quantizer = new(palette, paletteOptions, transparencyIndex, transparentColor);
using IQuantizer<TPixel> frameQuantizer = quantizer.CreatePixelSpecificQuantizer<TPixel>(this.configuration, quantizer.Options);
Expand Down
4 changes: 2 additions & 2 deletions src/ImageSharp/Formats/Icon/IconEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,8 @@ internal void Encode<TPixel, TProvider>(Image<TPixel> image, Stream stream, int
});
}

// Don't dither if we have a palette. We want to preserve as much information as possible.
return new PaletteQuantizer(colorTable.Value, new QuantizerOptions { Dither = null });
// Don't dither, and match colors exactly, if we have a palette. We want to preserve as much information as possible.
return new PaletteQuantizer(colorTable.Value, new QuantizerOptions { Dither = null, ColorMatchingMode = ColorMatchingMode.Exact });
}

/// <summary>
Expand Down
9 changes: 7 additions & 2 deletions src/ImageSharp/Formats/Png/PngEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1733,8 +1733,13 @@ private void SanitizeAndSetEncoderOptions<TPixel>(
if (metadata.ColorTable?.Length > 0)
{
// We can use the color data from the decoded metadata here.
// We avoid dithering by default to preserve the original colors.
QuantizerOptions options = new() { Dither = null, TransparentColorMode = encoder.TransparentColorMode };
// We avoid dithering and match colors exactly to preserve the original colors.
QuantizerOptions options = new()
{
Dither = null,
ColorMatchingMode = ColorMatchingMode.Exact,
TransparentColorMode = encoder.TransparentColorMode
};
this.quantizer = new PaletteQuantizer(metadata.ColorTable.Value, options);
}
else
Expand Down
21 changes: 21 additions & 0 deletions tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -484,4 +484,25 @@ private static void TestBmpEncoderCore<TPixel>(
// Does DebugSave & load reference CompareToReferenceInput():
image.VerifyEncoder(provider, "bmp", bitsPerPixel, encoder, customComparer);
}

[Fact]
public void Encode_1BitWithPaletteQuantizer_KeepsQuantizerOptions()
{
// The 1-, 2- and 4-bit paths build their own quantizer options, so they must keep the exact color matching of
// the configured quantizer.
using Image<Rgba32> image = NearColorPalette.CreateImage();
QuantizerOptions options = new() { Dither = null, ColorMatchingMode = ColorMatchingMode.Exact };
BmpEncoder encoder = new()
{
BitsPerPixel = BmpBitsPerPixel.Bit1,
Quantizer = new PaletteQuantizer(NearColorPalette.Palette, options)
};

using MemoryStream memStream = new();
image.Save(memStream, encoder);
memStream.Position = 0;
using Image<Rgba32> output = Image.Load<Rgba32>(memStream);

ImageComparer.Exact.VerifySimilarity(image, output);
}
}
28 changes: 28 additions & 0 deletions tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -454,4 +454,32 @@ public void GifEncoder_CanDecode_AndEncode_Issue3142<TPixel>(TestImageProvider<T
static bool Predicate(int i, int _) => i % 8 == 0; // Image has many frames, only compare a selection of them.
image.CompareDebugOutputToReferenceOutputMultiFrame(provider, ImageComparer.Exact, extension: "gif", predicate: Predicate);
}

[Theory]
[InlineData(FrameColorTableMode.Global)]
[InlineData(FrameColorTableMode.Local)]
public void Encode_PaletteFromMetadata_KeepsExactColors(FrameColorTableMode colorTableMode)
{
using Image<Rgba32> image = NearColorPalette.CreateImage();
GifMetadata metadata = image.Metadata.GetGifMetadata();
GifFrameMetadata frameMetadata = image.Frames.RootFrame.Metadata.GetGifMetadata();
metadata.ColorTableMode = colorTableMode;
frameMetadata.ColorTableMode = colorTableMode;

if (colorTableMode == FrameColorTableMode.Global)
{
metadata.GlobalColorTable = NearColorPalette.Palette;
}
else
{
frameMetadata.LocalColorTable = NearColorPalette.Palette;
}

using MemoryStream stream = new();
image.Save(stream, new GifEncoder());
stream.Position = 0;
using Image<Rgba32> output = Image.Load<Rgba32>(stream);

ImageComparer.Exact.VerifySimilarity(image, output);
}
}
17 changes: 17 additions & 0 deletions tests/ImageSharp.Tests/Formats/Icon/Ico/IcoEncoderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,4 +172,21 @@ public void BmpEntry_WritesPartialAlphaMaskByte(int width)

Assert.Equal((byte)(0b10000000 >> bitIndex), mask[byteIndex]);
}

[Fact]
public void Encode_PaletteFromMetadata_KeepsExactColors()
{
using Image<Rgba32> image = NearColorPalette.CreateImage();
IcoFrameMetadata metadata = image.Frames.RootFrame.Metadata.GetIcoMetadata();
metadata.Compression = IconFrameCompression.Bmp;
metadata.BmpBitsPerPixel = BmpBitsPerPixel.Bit8;
metadata.ColorTable = NearColorPalette.Palette;

using MemoryStream stream = new();
image.Save(stream, new IcoEncoder());
stream.Position = 0;
using Image<Rgba32> output = Image.Load<Rgba32>(stream);

ImageComparer.Exact.VerifySimilarity(image, output);
}
}
47 changes: 47 additions & 0 deletions tests/ImageSharp.Tests/Formats/NearColorPalette.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.

using SixLabors.ImageSharp.PixelFormats;

namespace SixLabors.ImageSharp.Tests.Formats;

/// <summary>
/// Provides an image and a palette for the reuse of a decoded palette. The two colors differ only in red: 8 and 12.
/// Both fall in the same bucket of the coarse color cache, which keeps 5 bits of each channel, so coarse matching maps
/// both colors to one entry. Only exact matching keeps each pixel's color.
/// </summary>
internal static class NearColorPalette
{
/// <summary>
/// The first palette color.
/// </summary>
private static readonly Rgba32 First = new(8, 16, 16, 255);

/// <summary>
/// The second palette color.
/// </summary>
private static readonly Rgba32 Second = new(12, 16, 16, 255);

/// <summary>
/// Gets the palette: the two colors of <see cref="CreateImage"/>.
/// </summary>
public static ReadOnlyMemory<Color> Palette { get; } = new[] { Color.FromPixel(First), Color.FromPixel(Second) };

/// <summary>
/// Creates an 8x2 image with the two palette colors in a checkerboard.
/// </summary>
/// <returns>The image.</returns>
public static Image<Rgba32> CreateImage()
{
Image<Rgba32> image = new(8, 2);
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
image[x, y] = (x + y) % 2 == 0 ? First : Second;
}
}

return image;
}
}
17 changes: 17 additions & 0 deletions tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -750,4 +750,21 @@ private static void TestPngEncoderCore<TPixel>(
using Image<TPixel> referenceImage = referenceDecoder.Decode<TPixel>(DecoderOptions.Default, fileStream);
ImageComparer.Exact.VerifySimilarity(referenceImage, imageSharpImage);
}

[Fact]
public void Encode_PaletteFromMetadata_KeepsExactColors()
{
using Image<Rgba32> image = NearColorPalette.CreateImage();
PngMetadata metadata = image.Metadata.GetPngMetadata();
metadata.ColorType = PngColorType.Palette;
metadata.BitDepth = PngBitDepth.Bit8;
metadata.ColorTable = NearColorPalette.Palette;

using MemoryStream stream = new();
image.Save(stream, new PngEncoder());
stream.Position = 0;
using Image<Rgba32> output = Image.Load<Rgba32>(stream);

ImageComparer.Exact.VerifySimilarity(image, output);
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading