Search code examples
pythonpngjpegpython-imaging-libraryfile-conversion

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.


Solution

  • 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