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.
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
"""
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With