// // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // namespace ImageProcessorCore.Quantizers { using System; using System.Threading.Tasks; /// /// Represents a quantized image where the pixels indexed by a color palette. /// public class QuantizedImage { /// /// Initializes a new instance of the class. /// /// The image width. /// The image height. /// The color palette. /// The quantized pixels. /// The transparency index. public QuantizedImage(int width, int height, Bgra32[] palette, byte[] pixels, int transparentIndex = -1) { Guard.MustBeGreaterThan(width, 0, nameof(width)); Guard.MustBeGreaterThan(height, 0, nameof(height)); Guard.NotNull(palette, nameof(palette)); Guard.NotNull(pixels, nameof(pixels)); if (pixels.Length != width * height) { throw new ArgumentException( $"Pixel array size must be {nameof(width)} * {nameof(height)}", nameof(pixels)); } this.Width = width; this.Height = height; this.Palette = palette; this.Pixels = pixels; this.TransparentIndex = transparentIndex; } /// /// Gets the width of this . /// public int Width { get; } /// /// Gets the height of this . /// public int Height { get; } /// /// Gets the color palette of this . /// public Bgra32[] Palette { get; } /// /// Gets the pixels of this . /// public byte[] Pixels { get; } /// /// Gets the transparent index /// public int TransparentIndex { get; } /// /// Converts this quantized image to a normal image. /// /// /// The /// public Image ToImage() { Image image = new Image(); int pixelCount = this.Pixels.Length; int palletCount = this.Palette.Length - 1; float[] bgraPixels = new float[pixelCount * 4]; Parallel.For(0, pixelCount, i => { int offset = i * 4; Color color = this.Palette[Math.Min(palletCount, this.Pixels[i])]; bgraPixels[offset] = color.R; bgraPixels[offset + 1] = color.G; bgraPixels[offset + 2] = color.B; bgraPixels[offset + 3] = color.A; }); image.SetPixels(this.Width, this.Height, bgraPixels); return image; } } }