LEARNING

NOOBI

Add Watermark To Your Image Before Uploading With Django

January 04 ,2023

Django
Pillow

Add Watermark To Your Image Before Uploading With Django


Ever wasted half an hour editing image in an online website just to have watermarks on it ?

Yeah I have 😭  .

 

 

It will only remove watermark if you are premium users or if you paid for it , which is fair , cause they need to pay bills too.

 

Frustration aside , adding watermark is a good feature that you might need in your next Django project or your already released projects . So in this blog , we will learn how to add watermark to your image before uploading it in the  server with Django .

 

Starting The Project :

 

Open your terminal and Type following commands :

 

mkdir watermark
cd watermark

 

We created new folder called watermark  using mkdir command  and went inside the directory using cd command .

 

This is where we add our django project . Before adding django , let's create a virtual environment  .

 

python -m venv env   # windows
env\Scripts\activate

virtualenv env  # linux or Mac
source env/bin/activate

#make sure you have install python and virtual environment before creating one

 

We activated virtual environment and within this environment , we will install django and pillow using command :

 

pip install django pillow

 

This will install django and pillow . You can check by using :

 

pip freeze 

python -m django --version 

 

Now , let's add django project using 

 

django-admin startproject djangomark
cd djangomark
python manage.py startapp core

 

We created project called djangomark  , went inside that directory and created an app called core .

Now add your app core  to the INSTALLED APPS  within settings.py inside mainproject directory.

 

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core' , # addhere
    
]

 

Inside the core folder ,  create a file called urls.py  .

djangomark

         |__core

              |____ ......

              |____ urls.py   # create 

         |___djangomark

 

Inside  urls.py add following code :

 

from django.urls import path
from .views import *

urlpatterns = [

]

 

Let's let's configure core-> urls.py inside djangomark->urls.py . 

Inside djangomark -> urls.py

djangomark

         |__core

              |____ urls.py

         |___djangomark

               |____ urls.py  <- here

 

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('core.urls')),
]

 

 

Now , Inside core -> views.py , create a view function to check everything .

 

from django.http import HttpResponse

def homeview(request):
    return HttpResponse("works fine")

 

Now , let's run the server and check everything .

 

python manage.py runserver

 

If everthing went correctly , you server should run . Then , open your browser and redirect to 

http://127.0.0.1:8000/ 

You should see  default " The install worked successfully! Congratulations! " . 

Now , add our views in core.urls.py .

 

from django.urls import path
from .views import homeview

urlpatterns = [
    path('',homeview , name='home')
]

 

We should see "works fine " httpResponse which we returned from homeview .

 

Creating Models :

 

Now in core -> models.py , let's add our database table using django ORM .

 

class ImageModel(models.Model):
    image = models.ImageField(blank=True, null=True, upload_to='blogpic')

 

We will use this simple model with only image field for now . Migrate this to make change in database .

 

python manage.py makemigrations
python manage.py migrate

 

Creating Templates:

 

Inside core  , create a folder like templates/core/home.html 

djangomark

         |__core

              |____ templates   

                       |___ core 

                              |___home.html

 

 Add following code in home.html

 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

</head>
<body>
	<div class="mt-4 container">
        <form action="." method="post" enctype="multipart/form-data">	
            {% csrf_token %}
            <input class="form-control" type="file" name="watermark-file" />
            <button class='mt-2 btn btn-primary' type="submit">Upload</button>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

 

make sure to add enctype="multipart/form-data"  as form attribute .

We added some html code with bootstrap cdn to style our element .

Inside homeview , return  this home.html file instead of httpresponse 

 

def homeview(request):
    return render(request,'core/home.html')

 

Now , in  http://127.0.0.1:8000/  , home.html is rendered .

Let's add code to upload image in our view function homeview .

 

 

from django.shortcuts import render,redirect
from .models import ImageModel

def homeview(request):
    if request.method=="POST":
        img = request.FILES.get('watermark-file')
        ImageModel.objects.create(image=img)
        return redirect('/')
    return render(request,'core/home.html')

 

We are using  function based views here .  We first check if the request method is POST or not . If it is not post then , it will

just render home.html .

 

      file = request.POST.get('watermark-file')
        ImageModel.objects.create(image=file)

 

We get the file uploaded from html using the name given to the input . Note : you must use the same name written in html input to get it's data in views. py . And then we create it using objects.create method . You don't need to call .save() when creating directly .

 

Creating Superuser :

 

Let's create superuser to check uploaded files .

 

python manage.py createsuperuser

 

Add superuser info  register ImageModel in core.admin.py 

 

from django.contrib import admin
from .models import ImageModel

admin.site.register(ImageModel)

 

Now ,in  http://127.0.0.1:8000/admin , image is uploaded . But before looking at the image , add media path for image url .

 

In settings.py  , add following code at bottom

import os
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')

 

In djangomark.urls.py , add some code .

 

from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static #add
from django.conf import settings #add

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('core.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

 

Now , uploading is done , let's go straight for adding watermark .🥳

 

Adding Watermark :

 

If you submit form now , it will upload image but there is no watermark on it . So , now let's add watermark to the uploaded image using our saviour pillow .

 

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

class ImageModel(models.Model):
    image = models.ImageField(blank=True, null=True, upload_to='blogpic')
    
    #creating watermark for photo
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        photo = Image.open(self.image.path)
        draw = ImageDraw.Draw(photo)
        font = ImageFont.load_default()
        width, height = photo.size
        myword = "Hello world !"
        margin = 10
        textwidth, textheight = draw.textsize(myword, font)
        x = width - textwidth - margin
        y = height - textheight - margin
        draw.text((x,y), myword, (255, 255, 255), font=font)
        photo.save(self.image.path)

 

 First we override our model save method . When we save our model , this function will run  . We use functions provided by pillow library .  First we open the image using  Image.open method . Then we draw on it using ImageDraw.draw .

 

font = ImageFont.load_default()

 

This gives default font provided my ImageFont . You cannot change it's size so you can use different font like arial .

You have to download the font before using it .

font = ImageFont.truetype("arial.ttf", 30)

 

textwidth, textheight = draw.textsize(mytime, font)
x = width - textwidth - margin
y = height - textheight - margin

 

This is just to calculate the position , so we can add our text in the bottom corner of the image .  Then we save the photo with watermarks on it . 

That's it . It is this easy .

 

Thank you 😁

 

2022 - Learningnoobi -All Rights Reserved