3

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.

Alireza
  • 6,497
  • 13
  • 59
  • 132
  • The png is probably transparent. JPG cant do transparency. It converts the transparent pixels RGBA to RGB's of 0,0,0 wich is black. Therefore you see nothing. – Patrick Artner Jun 07 '18 at 11:18
  • @PatrickArtner So I should just store the PNG as is? Isn't there a way to make the background white/black based on image color? – Alireza Jun 07 '18 at 11:20
  • Sure. Find out what foregroundcolors are used and set the transparent ones to none of those. But what do you want to accomplish with it? If you paste a transparent icon png onto something you only see whats to be seen - if you convert it to jpg you got a certain fixed backgroundcolor - if you put this on a different colored background you get ugly squares/rectangle of color-mismatches ... – Patrick Artner Jun 07 '18 at 11:35
  • Doesn't matter that the file size increases? JPG is a file format witch uses a real compressing method without changing the color depth. It can reduce the file size dramatically, infinitely variable, but in the same way with loss of quality. Usually JPG is recommend on photos, because of there wide color profile. A JPG with 80% compression could have a small loss of visual quality which most people don't recognize at all. You can use the PNG 24bit for photos as well, but with bigger file size. Additionally you can use PNG 8bit for graphics like logos or charts. There the color palette is reduc – UID Pro Berlin Jun 07 '18 at 13:06

1 Answers1

9

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

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69