From dbcb389d7361f15a3b7912b4104538188d78edd9 Mon Sep 17 00:00:00 2001 From: Ed Swartz Date: Sun, 31 May 2015 23:59:28 -0500 Subject: [PATCH] Add PNMImage premultiply/unpremultiply methods. --- panda/src/pnmimage/pnmImage.cxx | 57 +++++++++++++++++++++++++++++++++ panda/src/pnmimage/pnmImage.h | 3 ++ 2 files changed, 60 insertions(+) diff --git a/panda/src/pnmimage/pnmImage.cxx b/panda/src/pnmimage/pnmImage.cxx index 692e26b11d..83b02a82b2 100644 --- a/panda/src/pnmimage/pnmImage.cxx +++ b/panda/src/pnmimage/pnmImage.cxx @@ -622,6 +622,63 @@ make_grayscale(float rc, float gc, float bc) { setup_rc(); } +//////////////////////////////////////////////////////////////////// +// Function: PNMImage::premultiply_alpha +// Access: Published +// Description: Converts an image in-place to its "premultiplied" +// form, where, for every pixel in the image, the +// red, green, and blue components are multiplied by +// that pixel's alpha value. +// +// This does not modify any alpha values. +//////////////////////////////////////////////////////////////////// +void PNMImage:: +premultiply_alpha() { + if (!has_alpha()) { + return; + } + + for (int y = 0; y < get_y_size(); y++) { + for (int x = 0; x < get_x_size(); x++) { + float alpha = get_alpha(x, y); + float r = get_red(x, y) * alpha; + float g = get_green(x, y) * alpha; + float b = get_blue(x, y) * alpha; + set_xel(x, y, r, g, b); + } + } +} + +//////////////////////////////////////////////////////////////////// +// Function: PNMImage::unpremultiply_alpha +// Access: Published +// Description: Converts an image in-place to its "straight alpha" +// form (presumably from a "premultiplied" form), +// where, for every pixel in the image, the red, +// green, and blue components are divided by that +// pixel's alpha value. +// +// This does not modify any alpha values. +//////////////////////////////////////////////////////////////////// +void PNMImage:: +unpremultiply_alpha() { + if (!has_alpha()) { + return; + } + + for (int y = 0; y < get_y_size(); y++) { + for (int x = 0; x < get_x_size(); x++) { + float alpha = get_alpha(x, y); + if (alpha > 0) { + float r = get_red(x, y) / alpha; + float g = get_green(x, y) / alpha; + float b = get_blue(x, y) / alpha; + set_xel(x, y, r, g, b); + } + } + } +} + //////////////////////////////////////////////////////////////////// // Function: PNMImage::reverse_rows // Access: Published diff --git a/panda/src/pnmimage/pnmImage.h b/panda/src/pnmimage/pnmImage.h index b01d5ec974..c970411d27 100644 --- a/panda/src/pnmimage/pnmImage.h +++ b/panda/src/pnmimage/pnmImage.h @@ -133,6 +133,9 @@ PUBLISHED: void make_grayscale(float rc, float gc, float bc); INLINE void make_rgb(); + void premultiply_alpha(); + void unpremultiply_alpha(); + BLOCKING void reverse_rows(); BLOCKING void flip(bool flip_x, bool flip_y, bool transpose);