Skip to content

Instantly share code, notes, and snippets.

@fabiocerqueira
Last active January 17, 2017 22:54
Show Gist options
  • Select an option

  • Save fabiocerqueira/fdb1952beff266ae96ecede53f42f8e9 to your computer and use it in GitHub Desktop.

Select an option

Save fabiocerqueira/fdb1952beff266ae96ecede53f42f8e9 to your computer and use it in GitHub Desktop.
Example PIL image on template
import base64
import StringIO
from django.template import engines
from django.http import HttpResponse
from PIL import Image
def example(request):
image = Image.new('RGB', (200, 200))
buffer = StringIO.StringIO()
image.save(buffer, "PNG")
img_str = base64.b64encode(buffer.getvalue())
template_code = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Image</title>
</head>
<body>
<img src="data:image/png;base64,{{ img_str }}">
</body>
</html>
"""
template = engines['django'].from_string(template_code)
return HttpResponse(template.render(context={'img_str': img_str}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment