You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本无法生成带出血位JPG:仅创建输出文件夹的解决方法

问题排查与修复:生成16图排版带出血位的JPG脚本

我编写了一段Python脚本,预期将单张图片处理为包含16个同图排版的带出血位JPG文件。目前脚本仅成功创建了输出文件夹,但未生成任何JPG文件。以下是我的代码:

from PIL import Image, ImageOps
import os

# Directory path for the input images
input_directory_path = r'C:\Users\User\Desktop\ScriptTest\jpgRearrangment'

# Output directory path
output_directory = os.path.join(input_directory_path, 'output_with_bleeds_layout')
os.makedirs(output_directory, exist_ok=True)

# Output dimensions for the new .jpg with bleeds
output_width = 1270  # 127mm at 300 DPI
output_height = 1780  # 178mm at 300 DPI

# Bleed dimensions
top_bleed = 50  # 5mm at 300 DPI
bottom_bleed = 50  # 5mm at 300 DPI
left_bleed = 42  # 3.5mm at 300 DPI
right_bleed = 42  # 3.5mm at 300 DPI

# Calculate the dimensions of each individual photo with bleeds
photo_width = (output_width - left_bleed - right_bleed) // 4
photo_height = (output_height - top_bleed - bottom_bleed) // 4

# Function to add bleeds to an image and save it
def add_bleeds_and_save(input_image_path, output_image_path):
    img = Image.open(input_image_path)

    # Resize the original image to match the individual photo dimensions
    img = img.resize((photo_width, photo_height), Image.ANTIALIAS)

    # Create a new image with the desired dimensions and white background
    new_img = Image.new('RGB', (output_width, output_height), (255, 255, 255))

    # Calculate the position to paste the resized original image into the layout with bleeds
    x_offset = left_bleed
    y_offset = top_bleed

    # Paste the resized original image into the layout with bleeds
    for i in range(4):
        for j in range(4):
            new_img.paste(img, (x_offset + j * photo_width, y_offset + i * photo_height))

    # Save the final image with bleeds
    new_img.save(output_image_path, 'JPEG')

# List all .jpg files in the input directory
jpg_files = [file for file in os.listdir(input_directory_path) if file.endswith('.jpg')]

# Process each .jpg file
for jpg_file in jpg_files:
    # Create an output image with bleeds and layout
    output_image_name = f'rearranged_with_bleeds_layout_{jpg_file}'
    output_image_path = os.path.join(output_directory, output_image_name)
    add_bleeds_and_save(os.path.join(input_directory_path, jpg_file), output_image_path)

    print(f'Processed: {jpg_file} -> {output_image_name}')

print("All .jpg files rearranged with bleeds and layout and saved.")

修复方案

针对脚本未生成JPG的问题,可从以下几个方向调整:

1. 解决PIL版本兼容性问题

Image.ANTIALIAS在较新版本的Pillow中已被废弃,替换为Image.Resampling.LANCZOS(Pillow 9.1.0+)或Image.LANCZOS(旧版本),避免因API报错导致脚本中断。

2. 修正文件扩展名匹配逻辑

Windows系统中文件扩展名大小写不敏感,原脚本仅匹配小写.jpg,需同时兼容.JPG等大写情况。

3. 添加异常捕获与日志输出

在文件处理环节添加异常捕获,明确报错原因(如文件损坏、路径错误等),方便排查问题。

4. 验证输入目录的文件存在性

在遍历文件前,先输出找到的JPG文件数量,确认脚本正确识别到输入文件。


修改后的完整代码
from PIL import Image, ImageOps
import os

# Directory path for the input images
input_directory_path = r'C:\Users\User\Desktop\ScriptTest\jpgRearrangment'

# Output directory path
output_directory = os.path.join(input_directory_path, 'output_with_bleeds_layout')
os.makedirs(output_directory, exist_ok=True)

# Output dimensions for the new .jpg with bleeds
output_width = 1270  # 127mm at 300 DPI
output_height = 1780  # 178mm at 300 DPI

# Bleed dimensions
top_bleed = 50  # 5mm at 300 DPI
bottom_bleed = 50  # 5mm at 300 DPI
left_bleed = 42  # 3.5mm at 300 DPI
right_bleed = 42  # 3.5mm at 300 DPI

# Calculate the dimensions of each individual photo with bleeds
photo_width = (output_width - left_bleed - right_bleed) // 4
photo_height = (output_height - top_bleed - bottom_bleed) // 4

# Function to add bleeds to an image and save it
def add_bleeds_and_save(input_image_path, output_image_path):
    try:
        img = Image.open(input_image_path)
        
        # 兼容不同Pillow版本的重采样算法
        resample_method = Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS
        # Resize the original image to match the individual photo dimensions
        img = img.resize((photo_width, photo_height), resample_method)

        # Create a new image with the desired dimensions and white background
        new_img = Image.new('RGB', (output_width, output_height), (255, 255, 255))

        # Calculate the position to paste the resized original image into the layout with bleeds
        x_offset = left_bleed
        y_offset = top_bleed

        # Paste the resized original image into the layout with bleeds
        for i in range(4):
            for j in range(4):
                new_img.paste(img, (x_offset + j * photo_width, y_offset + i * photo_height))

        # Save the final image with bleeds
        new_img.save(output_image_path, 'JPEG', quality=95)
        return True
    except Exception as e:
        print(f"Error processing {input_image_path}: {str(e)}")
        return False

# List all .jpg files (case-insensitive) in the input directory
jpg_files = [file for file in os.listdir(input_directory_path) 
             if file.lower().endswith('.jpg')]

# Check if any JPG files are found
if not jpg_files:
    print(f"No JPG files found in directory: {input_directory_path}")
else:
    print(f"Found {len(jpg_files)} JPG file(s) to process.")
    # Process each .jpg file
    for jpg_file in jpg_files:
        # Create an output image with bleeds and layout
        output_image_name = f'rearranged_with_bleeds_layout_{jpg_file}'
        output_image_path = os.path.join(output_directory, output_image_name)
        success = add_bleeds_and_save(os.path.join(input_directory_path, jpg_file), output_image_path)
        if success:
            print(f'Processed: {jpg_file} -> {output_image_name}')
        else:
            print(f'Failed to process: {jpg_file}')

print("Processing completed.")

内容的提问来源于stack exchange,提问作者zoterpeter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 02:36:05