Reputation: 1320
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.
Upvotes: 1
Views: 3773
Reputation: 18133
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)
bg.paste(im, (0,0), im)
allows im's
alpha channel to act as a mask over your background image. (0,0)
paste your
image perfectly over your backgroundbg.save("file.jpg", quality=95)
; quality=95
ensures the highest quality from PIL
Upvotes: 1