首页 > 解决方案 > 我目前正在阅读“用 Python 自动化无聊的东西”,但我不知道为什么我的自动添加徽标和调整图像大小的项目不起作用

问题描述

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

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

我希望输出将是添加徽标和调整大小图像的文件夹,但是由于代码不起作用,因此什么也没有发生。

标签: pythonpython-3.xpython-imaging-library

解决方案


您的代码有两个问题:

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

有了这些提示,您应该很容易修复代码。


推荐阅读