Trasform code to create a cover image into a class (Pyhton and PIL)

This time we will dig into the code to make images to use classes instead of a non well organized code to make images for the covers of posts and videos.

The code

The class APP with the __init__ method

from PIL import Image, ImageFont, ImageDraw
import os

class App:
    def __init__(self, title="", subtitle="", image="", bg="", num=1):
        self.size = 640, 400
        self.bg = bg
        self.img = image
        self.shrink_ratio = 2 # use this in case you need to resize the image in the middle
        self.font = "arial", 38
        self.title = title
        self.subtitle = subtitle
        self.filename = "output\\" + self.img[:-4] + str(num) + "_cover.png" # do not need to change this
        self.fnt = ImageFont.truetype(self.font[0], self.font[1])
        self.fnt2 = ImageFont.truetype("arial", 28)
        self.imgb = Image.new("RGB", (self.size), color=self.bg)

The method of the class App to “shrink” the images (it’s on the same level of indentation of the __init__ method.

    def shrink(self, link, ratio=2):
        """Returns an image that is half of the original if ratio=2"""
        img = Image.open(link)
        w,h = img.size
        w = w // ratio # 2 is 50%
        h = h // ratio
        img = img.resize((w,h), Image.ANTIALIAS)
        return img

The create_image and middle method

    def middle(self, img, m=2):
        """Return the coordinates to place the image in the middle"""
        return self.size[0] // m - img.size[0] // m, self.size[1] // 2 - img.size[1] //  4

    def create_image(self):
       self.img_middle = self.shrink(self.img, self.shrink_ratio)
       self.draw = ImageDraw.Draw(self.imgb)
       self.title = self.title
       self.subtitle = self.subtitle
       self.draw.text((48,30), self.title, font=self.fnt)
       self.draw.text((50,115), self.subtitle, font=self.fnt2)
       self.half4 = (self.middle(self.img_middle,2))
       self.imgb.paste(self.img_middle, self.half4, self.img_middle)
       self.imgb.save(self.filename)
       self.imgb.show()

Ways to create images with the code above

Now that we have seen the code to make the images, we can see how to make the istance of the app to create the images. First you create the istance and then you call the method create_image().

The approach with the class makes it easy to leave the data for an image (commented maybe or without the create_image method call), so that you can reuse the old data to recreate them or changing them sligthly. You can also see anther useful way to use the istances at the end of this post.

To create an image with an istance of App:

cover = App(title="Make a cover image with Python",
        subtitle="Re-organize the code into a class.",
        image="logo.png",
        bg= "darkgreen")
cover.create_image()

As I said, using a class makes it easier to use more istances of it so that, as in the example below, you can make many covers with something in common and something different in just one click. This could be useful when you have to upload an entire playlist of videos and you do not want to spend a lot of time making all the covers one by one, even if they are quite similar. By the way, I am using this code and I am gonna use it for my playlists.

color = ["darkred","coral","darkgreen","lightblue"]
sub = ["The intro","The second episode","The third episode", "The final episode"]
for x in range(1, 5):
    img2 = App(title= f"Example n. {x}",
            subtitle= sub[x-1],
            image="logo.png",
            bg=color[x-1],
            num = x)
    # img2.create_image()

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.