I use Image.new create a image object in a django view, I want to show it in webpages.
x = Image.new('RGB',(400,400)) return HttpResponse(x.show(), mimetype="image/png")
doesn't work.
How can I covert a image object to a image raw binary?
I use Image.new create a image object in a django view, I want to show it in webpages.
x = Image.new('RGB',(400,400)) return HttpResponse(x.show(), mimetype="image/png")
doesn't work.
How can I covert a image object to a image raw binary?
You can embed base64 images into an <img src=
so you could try converting your PIL image to base64.
from PIL import Image
import StringIO
x = Image.new('RGB',(400,400))
output = StringIO.StringIO()
x.save(output, "PNG")
contents = output.getvalue().encode("base64")
output.close()
return HttpResponse('<img src="data:image/png;base64,' + contents + ' />')
You have 2 options:
The first option is the prefered one. The code should be something like:
x = Image.new() # The same stuff than yours
x.save(MEDIA_ROOT + "/generated_images/the_name_of_the_image.jpg", "JPEG")
return HttpResponse(
"<img src="%s/%s />" % (MEDIA_URL, "/generated_images/the_name_of_the_image.jpg")
)
If you want, you can read that in base64 (see: Encoding an image file with base64) And display it:
base64_img = get_base_64()
return HttpResponse('<img alt="Embedded Image" src="data:image/jpeg;base64," % base64_img />')
There is also a third way to accomplish this by having the view return the raw image so that the view's url can be referenced in the src attribute of the image tag.
Building on the examples others have used, the view that returns a dynamically generated image would look something like this:
from PIL import Image
import StringIO
def dynamic_image(request):
image = Image.new('RGB', (400, 400))
output = StringIO.StringIO()
image.save(output, 'PNG')
contents = output.getvalue()
output.close()
return HttpResponse(contents, content_type='image/png')
urls.py would reference this as:
urlpatterns = [
path('image', views.dynamic_image, name="dynamic_image")
]
Finally in the HTML, reference the view in the IMG tag:
<div>
<img src="{% url 'dynamic_image' %}" />
</div>
There is nothing wrong with the other approaches but they focus on returning HTML when Django views can return more than just HTML.