Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding logo to a cat image in Python

For the captioned, here's the code (courtesy Automate the Boring Stuff) and I'd tweaked it a bit.

import os
from PIL import Image

SQUARE_FIT_SIZE = 300
LOGO_FILENAME = 'catlogo.png'

logoIm = Image.open(LOGO_FILENAME)
logoWidth, logoHeight = logoIm.size

# Loop over all files in the working directory.
for filename in os.listdir('.'):
    if not (filename.endswith('.png') or filename.endswith('.jpg')) \
       or filename == LOGO_FILENAME:
        continue # skip non-image files and the logo file itself

    im = Image.open(filename)
    width, height = im.size

    # Add logo.
    print('Adding logo to %s...' % (filename))
    im.paste(logoIm, (width - logoWidth, height - logoHeight), logoIm)

    # Save changes.
    im.save('Cat with Logo.png')

Cat Logo

Cat Image

For some reason, the logo failed to be added at the end. Is something wrong with the save command?

like image 759
srkdb Avatar asked Apr 08 '26 16:04

srkdb


1 Answers

I realized resizeAndAddLogo.py resizes the file to which the logo is pasted on, not the logo size proportioned to the file. We don't want that. So I changed the script to change logo size with the ratio of 1/5 to the image file.

...
# Resize the logo.
print(f'Resizing logo to fit {filename}...')
sLogo = logoIm.resize((int(width / 5), int(height / 5)))
sLogoWidth, sLogoHeight = sLogo.size

# Add the logo.
print(f'Adding logo to {filename}...')
im.paste(sLogo, (width - sLogoWidth, height - sLogoHeight), sLogo)
...

At this point, I don't need SQUARE_FIT_SIZE = 300, so I deleted it and made the code shorter. Here's my full script.

import os
from PIL import Image

LOGO_FILENAME = 'catlogo.png'
logoIm = Image.open(LOGO_FILENAME)
os.makedirs('withLogo', exist_ok=True)

# Loop over all files in the working directory.
for filename in os.listdir():
    if not (filename.endswith('.png') or filename.endswith('.jpg')) or filename == LOGO_FILENAME:
        continue

    im = Image.open(filename)
    width, height = im.size

    # Resize the logo.
    print(f'Resizing logo to fit {filename}...')
    sLogo = logoIm.resize((int(width / 5), int(height / 5)))
    sLogoWidth, sLogoHeight = sLogo.size

    # Add the logo.
    print(f'Adding logo to {filename}...')
    im.paste(sLogo, (width - sLogoWidth, height - sLogoHeight), sLogo)

    # Save changes.
    im.save(os.path.join('withLogo', filename))

Note that resized logo should be assigned to be used in loop.

And this one of the resulted images.

enter image description here

like image 112
harryghgim Avatar answered Apr 10 '26 06:04

harryghgim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!