I'm trying to take an UploadedFile
, convert it to a PIL Image
object to thumbnail it, and the convert the PIL Image
object that my thumbnailer returns back into a File
object. How the heck can I do this?
views:
56answers:
1
+1
A:
I've had to do this in a few steps, imagejpeg() in php requires a similar process. Not to say theres no way to keep things in memory, but this method gives you a file reference to both the original image and thumb (usually a good idea in case you have to go back and change your thumb size).
- save the file
- open it from filesystem with PIL,
- save to a temp directory with PIL,
- then open as a Django file for this to work.
YourModel(Model): img = models.ImageField(upload_to='photos') thumb = models.ImageField(upload_to='thumbs')
#in upload code
uploaded = request.FILES['photo']
from django.core.files.base import ContentFile
file_content = ContentFile(uploaded.read())
new_file = YourModel()
#1 - get it into the DB and file system so we know the real path
new_file.img.save(str(new_file.id) + '.jpg', file_content)
new_file.save()
from PIL import Image
import os.path
#2, open it from the location django stuck it
thumb = Image.open(new_file.img.path)
thumb.thumbnail(100, 100)
#make tmp filename based on id of the model
filename = str(new_file.id)
#3. save the thumbnail to a temp dir
temp_image = open(os.path.join('/tmp',filename), 'w')
thumb.save(temp_image, 'JPEG')
#4. read the temp file back into a File
from django.core.files import File
thumb_data = open(os.path.join('/tmp',filename), 'r')
thumb_file = File(thumb_data)
new_file.thumb.save(str(new_file.id) + '.jpg', thumb_file)
Lincoln B
2010-09-16 02:53:05