ladybird/Userland/Libraries/LibGfx/MedianCut.h
Lucas CHOLLET 1ba8a6f80f LibGfx: Add an implementation of the MedianCut algorithm
This is useful to find the best matching color palette from an existing
bitmap. It can be used in PixelPaint but also in encoders of old image
formats that only support indexed colors e.g. GIF.
2024-05-18 18:30:07 +02:00

54 lines
1.1 KiB
C++

/*
* Copyright (c) 2024, Lucas Chollet <lucas.chollet@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/HashMap.h>
#include <AK/Vector.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/Color.h>
namespace Gfx {
class ColorPalette {
public:
struct ColorAndIndex {
Color color;
size_t index;
};
ColorPalette(Vector<Color> palette, HashMap<Color, ColorAndIndex> conversion_table)
: m_palette(move(palette))
, m_conversion_table(move(conversion_table))
{
}
Vector<Color> const& palette() const
{
return m_palette;
}
Color closest_color(Color input) const
{
return m_palette[index_of_closest_color(input)];
}
u32 index_of_closest_color(Color input) const
{
if (auto const result = m_conversion_table.get(input); result.has_value())
return result->index;
TODO();
}
private:
Vector<Color> m_palette;
HashMap<Color, ColorAndIndex> m_conversion_table;
};
ErrorOr<ColorPalette> median_cut(Bitmap const& bitmap, u16 palette_size);
}