Professional project
Python code solution and explanation
Pillow, PIL, text watermark
introduction
Traditionally, adding a watermark to an image would require the use of image editing software such as Photoshop. Which can take lots of time, especially if you have more than one photo.
However, with this program, watermarking can be done automatically. For example, if you wish to post photos on Instagram with a website or logo added, the program can automatically apply the watermark to each image.
solution
First, let’s import the required libraries.
from PIL import Image, ImageDraw, ImageFont
Now I have a file called original_puppy.jpg, containing a picture of a puppy. We can open this image using the filename and show it. Make sure that the photo is in the same directory.
filename = "original_puppy.jpg"
image = Image.open(filename)
image.show()
Next, we need to use a watermark. For this example, we’ll use a text one. To get it into the bottom right corner I used this code:
width, height = image.size
draw = ImageDraw.Draw(image)
text = "Gursehaj" # watermarked
font = ImageFont.truetype('arial.ttf', 100)
textwidth, textheight = draw.textsize(text, font)
margin = 40
x = width - textwidth - margin
y = height - textheight - margin
Finally, to display it, we use the x and y variables, the text, and the font, and show and save that to a new image called “watermark_puppy.jpg”.
draw.text(xy=(x, y), text=text, font=font)
image.show()
image.save('watermark_puppy.jpg')
final code
To view my full code, please visit my GitHub repository: https://github.com/Gursehaj-Singh/image-watermark
filename = "original_puppy.jpg"
image = Image.open(filename)
image.show()
width, height = image.size
draw = ImageDraw.Draw(image)
text = "Gursehaj" # watermarked
font = ImageFont.truetype('arial.ttf', 100)
textwidth, textheight = draw.textsize(text, font)
margin = 40
x = width - textwidth - margin
y = height - textheight - margin
draw.text(xy=(x, y), text=text, font=font)
image.show()
image.save('watermark_puppy.jpg')
Example run
further steps
Now that we’ve created a simple image watermark program, we can make something even more complicated.
For example, if you had 1000 photos for your business and don’t want to manually photoshop a watermark on every single one, you can simply add a for loop to go through each image and then watermark it.
Or if you don’t want a text watermark, you can also upload images. You can even take a small section of the original picture, and then use that as a watermark!
Now you know what the possibilities for this image watermark program are. Hope you enjoyed my program.