Alireza
Alireza

Reputation: 6868

How to Covert PNG to JPEG using Pillow while image color is black?

I have looked at the below links to see how to convert PNG to JPG:

The conversion works as expected, but when the image color itself is not black! I have the below image: pen edit

And the code is:

im.convert('RGB').save('test.jpg', 'JPEG')

It makes the whole picture black. How should I convert this PNG in correct format and color? The color can be anything from black to white.

Upvotes: 3

Views: 4053

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51683

Convert it like this, only thing to do is find out which backgroundcolor to set:

from PIL import Image
im = Image.open(r"C:\pathTo\pen.png")

fill_color = (120,8,220)  # your new background color

im = im.convert("RGBA")   # it had mode P after DL it from OP
if im.mode in ('RGBA', 'LA'):
    background = Image.new(im.mode[:-1], im.size, fill_color)
    background.paste(im, im.split()[-1]) # omit transparency
    im = background

im.convert("RGB").save(r"C:\temp\other.jpg")

recolored

Upvotes: 10

Related Questions