// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using SixLabors.ImageSharp.PixelFormats;
namespace SixLabors.ImageSharp.Processing.Processors.Quantization;
///
/// Allows the quantization of images pixels using color palettes.
///
public class PaletteQuantizer : IQuantizer
{
private readonly ReadOnlyMemory colorPalette;
///
/// Initializes a new instance of the class.
///
/// The color palette.
public PaletteQuantizer(ReadOnlyMemory palette)
: this(palette, new QuantizerOptions())
{
}
///
/// Initializes a new instance of the class.
///
/// The color palette.
/// The quantizer options defining quantization rules.
public PaletteQuantizer(ReadOnlyMemory palette, QuantizerOptions options)
{
Guard.MustBeGreaterThan(palette.Length, 0, nameof(palette));
Guard.NotNull(options, nameof(options));
this.colorPalette = palette;
this.Options = options;
}
///
public QuantizerOptions Options { get; }
///
public IQuantizer CreatePixelSpecificQuantizer(Configuration configuration)
where TPixel : unmanaged, IPixel
=> this.CreatePixelSpecificQuantizer(configuration, this.Options);
///
public IQuantizer CreatePixelSpecificQuantizer(Configuration configuration, QuantizerOptions options)
where TPixel : unmanaged, IPixel
{
Guard.NotNull(options, nameof(options));
// Always use the palette length over options since the palette cannot be reduced.
TPixel[] palette = new TPixel[this.colorPalette.Length];
Color.ToPixel(this.colorPalette.Span, palette.AsSpan());
return new PaletteQuantizer(configuration, options, palette);
}
}