//
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
//
namespace ImageProcessor.Formats
{
using System;
///
/// 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.
public QuantizedImage(int width, int height, Bgra32[] palette, byte[] pixels)
{
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;
}
///
/// 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; }
///
/// 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];
for (int i = 0; i < pixelCount; i++)
{
int offset = i * 4;
Bgra32 color = this.Palette[Math.Min(palletCount, this.Pixels[i])];
bgraPixels[offset + 0] = color.B;
bgraPixels[offset + 1] = color.G;
bgraPixels[offset + 2] = color.R;
bgraPixels[offset + 3] = color.A;
}
image.SetPixels(this.Width, this.Height, bgraPixels);
return image;
}
}
}