1
votes

i'm using Django 1.6.2 and Python 3.3.5 and Pillow 2.3.0.

What is the best way to convert an png/gif image to an jpg image in Django, so that the output-file is nearly the same as the uploaded file? (transparency => white)

I have tried a couple of solutions like:

import Image
im = Image.open("infile.png")
im.save("outfile.jpg")

or

from PIL import Image
im = Image.open("file.png")
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im,im)
bg.save("file.jpg")

The problem is i found no satisfied solution which handles gif, png (hard-edged mask, soft-edged mask).

Any ideas?

EDIT:

Ok, i'm using ImageKit, what does exactly what i want to do.

1
FYI, JPG does not support any kind of transparency.ThiefMaster
And GIF doesn't support alpha transparency, like PNG does.Lukas Graf
no satisfied solution which handles all kind of files??laike9m

1 Answers

1
votes

Use:

from PIL import Image
im = Image.open("file.png")
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im, (0,0), im)
bg.save("file.jpg", quality=95)
  • Passing in the second image in bg.paste(im, (0,0), im) allows im's alpha channel to act as a mask over your background image.
  • The coordinates (0,0) paste your image perfectly over your background
  • bg.save("file.jpg", quality=95); quality=95 ensures the highest quality from PIL