[Django]-Image watermark using PIL in django

1👍

Assume you have the server-side url of image as: Photo.image_url

You can use the following view function to return an watermarked image:

from PIL import Image
from django.core.servers.basehttp import FileWrapper
from django.http import StreamingHttpResponse

def render_image_with_watermark(request, pk, text):

    # pk is the primary key of photo model
    photo = get_object_or_404(Photo, pk=pk)

    # watermark the photo and save it to a temp file
    tmp_name = tempfile.mktemp()

    # this function was introduced in:
    # http://www.pythoncentral.io/watermark-images-python-2x/
    add_watermark(photo.image_url, text, out_file=tmp_name, angle=23, opacity=0.25)

    # render the watermarked photo to response
    wrapper = FileWrapper(open(photo.image_url, 'rb'))
    response = StreamingHttpResponse(wrapper, 'image/jpeg')
    response['Content-Length'] = os.path.getsize(photo.image_url)
    response['Content-Disposition'] = 'attachment; filename=photo.jpg'

    return response

In case you want to render all images with watermarked, you can first make the render_image_with_watermark view above has a url:

# urls.py
urlpatterns = patterns('',
    url(r'^photo/(?P<pk>\d+)/$', 'render_image_with_watermark', name='render_image_with_watermark'),
    ...
)

After doing this, try to visit the url /photo/photo.pk,if success, it will render the image directly.

Then, change your showimage.html template:

{% extends 'base.html'%}
{%block title%}{%endblock%}
{%block content%}
{% load endless %}
<div class="container" >
    <div class="row mt" style="padding-top:0px; margin-top:10px;">
        <ul class="grid effect-2" id="grid">
        {% paginate 40 photo_list %}
        {% for photo in photo_list%}
              {% if photo.approved%}
              <li><a href = "{% url 'download_image' photo.id %}">


                     <!-- ATTENTION HERE -->
                     <img src={% url 'render_image_with_watermark' pk=photo.id %} alt = 'sample photo' /></a>

              </li>
              {%endif%}
        {% endfor %}
        </ul>
    </div><!-- row -->
</div><!-- container -->
<p>{%show_more%}</p>
{%endblock%}

Have a try.

3👍

Disclaimer: I’m the author of the watermark tutorial

Additional info: For website output, here are the changes:-

 import os, sys, StringIO ## change line 2 ##

 def add_watermark(in_file, angle=23, opacity=0.25): ## change line 6 ##
     out_file = StringIO.StringIO() ## insert after line 6 ##
     ...
     return out_file.getValue() ## insert after 24 ##

To use it: myImage = add_watermark(photo_image). Create the HTTP header and output with myImage. Basically we’re saving the JPG to StringIO and using getValue() to read it.

Also check Mark’s fork which overlays an image instead.

Leave a comment