Reputation: 701
In my Django app, Users can upload images. I want to save every uploaded image as a PNG. I've been trying to do this with PIL but it's not working. It still seems to be saving as the original image type (whatever the user uploaded it as). What am I doing wrong?
if form.cleaned_data['dataset_image']:
# dataset.dataset_image = form.cleaned_data['dataset_image']
name = 'dataset%s.png' % (dataset.id)
size = (200, 200)
try:
im = Image.open(form.cleaned_data['dataset_image'])
im.save(name, 'PNG')
print "saved file: ", im
except IOError:
# dont' save the image
pass
When I upload a jpg (that I want to convert to png), the print statement gives this: saved file: <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=628x419 at 0x107354F80>
Upvotes: 0
Views: 1112
Reputation: 9796
The print statement refers to the Image
object when you opened the file. It used the JpegImagePlugin
class because it is a jpeg image. However, when you call the method save()
, you save the image based on the extension of the requested filename, in this case, png.
Try this if you aren't convinced.
try:
im = Image.open(form.cleaned_data['dataset_image'])
im.save(name)
png_img = Image.open(name)
print "saved file: ", png_img # it's more clean to print `png_img.format`
By the way, just calling im.save(name)
will also do in this case, since name
already has the extension and the method will figure out you want it in that format.
Upvotes: 0