gpt4 book ai didi

python - 在 Python 中将 Logo 添加到猫图像

转载 作者:行者123 更新时间:2023-12-05 05:15:02 24 4
gpt4 key购买 nike

对于标题,这是代码(由 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')

Cat Logo

Cat Image

由于某些原因,最后添加logo失败。 save 命令有问题吗?

最佳答案

我意识到 resizeAndAddLogo.py 会调整粘贴 Logo 的文件的大小,而不是调整与文件成比例的 Logo 大小。我们不想要那样。所以我更改了脚本以将 Logo 大小更改为图像文件的 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))

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

这是生成的图像之一。

enter image description here

关于python - 在 Python 中将 Logo 添加到猫图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51995182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com