Posts

Showing posts with the label Rgba

Convert RGBA PNG To RGB With PIL

Image
Answer : Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG support for sorl thumbnails. from PIL import Image png = Image.open(object.logo.path) png.load() # required for png.split() background = Image.new("RGB", png.size, (255, 255, 255)) background.paste(png, mask=png.split()[3]) # 3 is the alpha channel background.save('foo.jpg', 'JPEG', quality=80) Result @80% Result @ 50% By using Image.alpha_composite , the solution by Yuji 'Tomita' Tomita become simpler. This code can avoid a tuple index out of range error if png has no alpha channel. from PIL import Image png = Image.open(img_path).convert('RGBA') background = Image.new('RGBA', png.size, (255,255,255)) alpha_composite = Image.alpha_composite(background, png) alpha_composite.save('foo.jpg', 'JPEG', quality=80) The transparent parts mostly have RGBA valu...

Convert RGBA To HEX

Answer : Since alpha value both attenuates the background color and the color value, something like this could do the trick: function rgba2rgb(RGB_background, RGBA_color) { var alpha = RGBA_color.a; return new Color( (1 - alpha) * RGB_background.r + alpha * RGBA_color.r, (1 - alpha) * RGB_background.g + alpha * RGBA_color.g, (1 - alpha) * RGB_background.b + alpha * RGBA_color.b ); } (Try it interactively: https://marcodiiga.github.io/rgba-to-rgb-conversion)