flashter flashter - 5 months ago 18
Python Question

ImageField from Django to PIL Image to send via HttpResponse

Im new here. Newbie in Django (and English) here. Im trying to get an image (I get the id of the image using a form via POST) from the database(ImageField), crop it with PIL Image and send it via HttpResponde. It doesnt give an error but when I receive the image "piece.jpg", it is a corrupt file. If I open it using notepad I can only see:

<PIL.Image.Image image mode=RGB size=46x75 at 0x3DEA790>


This is my code in views.py:

from PIL import Image

def function(request):

if request.method == 'POST':

id = request.POST.get('id')
object = Document.objects.get(pk=id)

im = Image.open(object.docfile)

left = 10
top = 10
right = 100
bottom = 100
cropped_image = im.crop( (left, top, right, bottom) )

response = HttpResponse(cropped_image, content_type='image/jpg')
response['Content-Disposition'] = 'attachment; filename="piece.jpg"'
return response


I tried sending just "object.docfile" and it works. But if I try to send "im" (which is a PIL image), it doesnt work.

Answer

HttpResponse expects string or an iterator. More details in docs:

https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse.init

Did you try something like this?

response = HttpResponse(mimetype='image/jpg')
cropped_image.save(response, "JPEG")
return response