Last active
January 17, 2017 22:54
-
-
Save fabiocerqueira/fdb1952beff266ae96ecede53f42f8e9 to your computer and use it in GitHub Desktop.
Example PIL image on template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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