gpt4 book ai didi

python - 我目前正在阅读 "Automate boring stuffs with Python",我不知道为什么我的自动添加 Logo 和调整图像大小项目不起作用

转载 作者:行者123 更新时间:2023-12-01 00:35:27 25 4
gpt4 key购买 nike

我是编码新手。所以,说实话,我不知道我在这里做错了什么

import os
from PIL import Image

SQUARE_FIT_SIZE = 900
LOGO_FILENAME = "24h.png"

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

os.makedirs("withLogo", exist_ok=True)

path = "/Users/mac/Desktop/水/71"
for filename in os.listdir("path"):

if not (filename.endswith('.png') or filename.endswith('.jpg')) \
or filename == LOGO_FILENAME:
im = Image.open(filename)
width, height = im.size
if width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE:
if width>height:
height = int((SQUARE_FIT_SIZE / width) * height)
width = SQUARE_FIT_SIZE
else:
width = int((SQUARE_FIT_SIZE / height) * width)
height = SQUARE_FIT_SIZE
print('Resizing %s...' % (filename))
im = im.resize((width, height))

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

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

我预计输出将是一个包含添加的 Logo 和调整大小的图像的文件夹,但由于代码不起作用,所以什么也没有发生。

最佳答案

您的代码有两个问题:

  1. 您正在使用相对路径。所以而不是

    os.makedirs("withLogo", exist_ok=True)
    path = "/Users/mac/Desktop/水/71"

    反转语句的顺序并使用 makedirs 的绝对路径:

    path = "/Users/mac/Desktop/水/71"
    target_path=os.path.join(path, "withLogo")
    os.makedirs(target_path, exist_ok=True)

    我还添加了一个新变量 target_path,您可以在稍后保存图像时使用它:

     im.save(os.path.join(target_path, filename))

    如果您使用相对路径,则当前工作目录将用作所有这些操作的根目录。

  2. 您使用的是字符串而不是变量:

    for filename in os.listdir("path"):

    此处不需要引号,因此很容易修复:

    for filename in os.listdir(path):

有了这些提示,您应该可以轻松修复代码。

关于python - 我目前正在阅读 "Automate boring stuffs with Python",我不知道为什么我的自动添加 Logo 和调整图像大小项目不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57820199/

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