Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: return image data from a view

I want a view to return image data. so something along the lines of

return HttpResponse(image_data, mimetype=”image/png”)

I know I can do a file.read() to get the image data, but because the image is small (like 1x1 px) I want to just store it as a string object (or whatever object I can copy and paste in my code). This way, I save myself the disk lookup everytime the view is hit.

How do i go about this? I'm sure this is easy, I'm just not sure what terms to use for search.

p.s. I know that one does not normally serve images this way with Django.

like image 977
w-- Avatar asked Dec 13 '11 01:12

w--


2 Answers

Here is a simple example from the django-openid project

def logo(request):
    return HttpResponse(
        OPENID_LOGO_BASE_64.decode('base64'), content_type='image/gif'
    )
    # Logo from http://openid.net/login-bg.gif
    # Embedded here for convenience; you should serve this as a static file
    OPENID_LOGO_BASE_64 = """
    R0lGODlhEAAQAMQAAO3t7eHh4srKyvz8/P5pDP9rENLS0v/28P/17tXV1dHEvPDw8M3Nzfn5+d3d
    3f5jA97Syvnv6MfLzcfHx/1mCPx4Kc/S1Pf189C+tP+xgv/k1N3OxfHy9NLV1/39/f///yH5BAAA
    AAAALAAAAAAQABAAAAVq4CeOZGme6KhlSDoexdO6H0IUR+otwUYRkMDCUwIYJhLFTyGZJACAwQcg
    EAQ4kVuEE2AIGAOPQQAQwXCfS8KQGAwMjIYIUSi03B7iJ+AcnmclHg4TAh0QDzIpCw4WGBUZeikD
    Fzk0lpcjIQA7
    """
like image 160
KS.Pan Avatar answered Oct 30 '22 14:10

KS.Pan


You may consider using base64. But you might find that the performance boost is almost irrelevant as your image will be stored in the disk cache. I would be interested to see the benchmarks of base64 decoding vs disk access. You may even find that this optimisation would have the opposite effect.

Edit: I found this page on the linux disk cache which you might interesting reading when making this decision. So long as your disk activity isn't too high, the chances of this tiny image being part of the disk cache seems likely.

like image 22
Steve Rukuts Avatar answered Oct 30 '22 13:10

Steve Rukuts