0

I want to convert .png image with transparency to .jpg with PIL in python. When i use the "convert" method it says that i cant handle the alpha background.

from PIL import Image
import os

i = Image.open('hi.png')
i.convert('RGB')
i.save(os.path.join(current_app.root_path, 'folder to be sved to', 'hi.jpg'))         

It should convert it to .jpg but throws this error 'OSError: cannot write mode RGBA as JPEG'

bjernie
  • 158
  • 3
  • 13
  • On my side, working well, Please share your image – Wang Liang Apr 24 '19 at 19:19
  • 1
    This was introduced in Pillow 4.2.0. See https://github.com/python-pillow/Pillow/blob/master/docs/releasenotes/4.2.0.rst#removed-deprecated-items: "Before Pillow 4.2.0, attempting to save an RGBA image as JPEG would discard the alpha channel. From Pillow 3.4.0, a deprecation warning was shown. From Pillow 4.2.0, the deprecation warning is removed and an :py:exc:`IOError` is raised." – B. Shefter Apr 24 '19 at 19:24

1 Answers1

4

convert() returns a converted copy of the image; it doesn't change the original. You need to create and save a new image, like so:

i = Image.open('hi.png')
new_i = i.convert('RGB')
new_i.save(os.path.join(current_app.root_path, 'folder to be sved to', 'hi.jpg'))    
B. Shefter
  • 877
  • 7
  • 19