From 8e441d402ba0e81798ccca49f8c48ba036dc5825 Mon Sep 17 00:00:00 2001 From: MacDue Date: Mon, 9 May 2022 00:01:21 +0100 Subject: [PATCH] LibGfx: Add Bitmap::solid_color() This function returns an Optional and is given an alpha_threshold. If all pixels above that alpha threshold are the same color, it returns the color, otherwise it returns an empty optional. --- Userland/Libraries/LibGfx/Bitmap.cpp | 17 +++++++++++++++++ Userland/Libraries/LibGfx/Bitmap.h | 2 ++ 2 files changed, 19 insertions(+) diff --git a/Userland/Libraries/LibGfx/Bitmap.cpp b/Userland/Libraries/LibGfx/Bitmap.cpp index 35ba62d702..56619440b9 100644 --- a/Userland/Libraries/LibGfx/Bitmap.cpp +++ b/Userland/Libraries/LibGfx/Bitmap.cpp @@ -608,4 +608,21 @@ bool Bitmap::visually_equals(Bitmap const& other) const return true; } +Optional Bitmap::solid_color(u8 alpha_threshold) const +{ + Optional color; + for (auto y = 0; y < height(); ++y) { + for (auto x = 0; x < width(); ++x) { + auto const& pixel = get_pixel(x, y); + if (has_alpha_channel() && pixel.alpha() <= alpha_threshold) + continue; + if (!color.has_value()) + color = pixel; + else if (pixel != color) + return {}; + } + } + return color; +} + } diff --git a/Userland/Libraries/LibGfx/Bitmap.h b/Userland/Libraries/LibGfx/Bitmap.h index 968ab77087..f556a25f52 100644 --- a/Userland/Libraries/LibGfx/Bitmap.h +++ b/Userland/Libraries/LibGfx/Bitmap.h @@ -240,6 +240,8 @@ public: [[nodiscard]] bool visually_equals(Bitmap const&) const; + [[nodiscard]] Optional solid_color(u8 alpha_threshold = 0) const; + private: Bitmap(BitmapFormat, IntSize const&, int, BackingStore const&); Bitmap(BitmapFormat, IntSize const&, int, size_t pitch, void*);