首页 > 解决方案 > 在 Python 中将徽标添加到猫图像

问题描述

对于标题,这是代码(由 Automate the Boring Stuff 提供),我对其进行了一些调整。

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')

猫标志

猫形象

由于某种原因,未能在最后添加徽标。save命令 有问题吗?

标签: pythonimage-processing

解决方案


我意识到resizeAndAddLogo.py调整徽标粘贴到的文件的大小,而不是与文件成比例的徽标大小。我们不希望那样。因此,我更改了脚本以将徽标大小更改为图像文件的 1/5。

...
# 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)
...

此时,我不需要SQUARE_FIT_SIZE = 300,所以我将其删除并缩短了代码。这是我的完整脚本。

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))

请注意,应分配调整大小的徽标以在循环中使用。

这是结果图像之一。

在此处输入图像描述


推荐阅读