Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to write an image to a Django HttpResponse()

I need to serve images securely to validated users only (i.e. they can't be served as static files). I currently have the following Python view in my Django project, but it seems inefficient. Any ideas for a better way?

def secureImage(request,imagePath):     response = HttpResponse(mimetype="image/png")     img = Image.open(imagePath)     img.save(response,'png')     return response 

(Image is imported from PIL.)

like image 625
k-g-f Avatar asked Jun 09 '10 04:06

k-g-f


2 Answers

Well, re-encoding is needed sometimes (i.e. applying an watermark over an image while keeping the original untouched), but for the most simple of cases you can use:

try:     with open(valid_image, "rb") as f:         return HttpResponse(f.read(), content_type="image/jpeg") except IOError:     red = Image.new('RGBA', (1, 1), (255,0,0,0))     response = HttpResponse(content_type="image/jpeg")     red.save(response, "JPEG")     return response 
like image 92
StefanNch Avatar answered Sep 28 '22 08:09

StefanNch


Make use of FileResponse
A cleaner way, here we dont have to worry about the Content-Length and Content-Type headers they are automatically set when they can be guessed from contents of open().

from django.http import FileResponse  def send_file(response):      img = open('media/hello.jpg', 'rb')      response = FileResponse(img)      return response 
like image 20
Sumithran Avatar answered Sep 28 '22 07:09

Sumithran