python - 我目前正在阅读“用 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))
我希望输出将是添加徽标和调整大小图像的文件夹,但是由于代码不起作用,因此什么也没有发生。
解决方案
您的代码有两个问题:
您正在使用相对路径。所以而不是
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))
如果您使用相对路径,则当前工作目录将用作所有这些操作的根目录。
您使用的是字符串而不是变量:
for filename in os.listdir("path"):
这里不需要引号,所以这很容易解决:
for filename in os.listdir(path):
有了这些提示,您应该很容易修复代码。
推荐阅读
- javascript - JavaScript throw 语句 *需要帮助*
- javascript - 移动鼠标时在 Firefox 中出现生涩的 javascript 动画
- android - 您的应用不符合 Google Play 政策,但确实如此
- rabbitmq - RabbitMQ Http Authentication Backend with SSL
- fortran - Undefined symbols for architecture x86_64 in a NLopt Fortran compilation
- python - Two-point Euclidean distance from csv file
- rust - 所有权转移后的变异变量
- r - 如何加入相似字符的数据集?
- swift - 以版本为条件的 Swift 扩展
- wpf - 使用 MVVM 的 WPF 自定义模式对话框