如何利用ChatGPT实现工作上的便利

由于工作的需要,要处理大量的图片成统一规格,多出来的位只要白底就可以, Photoshop的Camera Raw只能缩小批量处理,网上虽有但要收费, 突然有日我问ChatGPT,刚问出来时我没有想用Python,因为本人对这类代码语言并不熟悉,但后来我发现Python是可以执行此类简单而且繁复又沉闷的工作,因而尝试逐步问,问完后发现自己想增加的问题又再问, 从而得到以下可以批量处理图片成统一尺寸,以下为得出来的代码。


from PIL import Image
import os

def process_images(folder):
    total_images = 0
    processed_images = 0
    for root, dirs, files in os.walk(folder):
        for filename in files:
            filepath = os.path.join(root, filename)
            if is_image_file(filepath):
                total_images += 1

    for root, dirs, files in os.walk(folder):
        for filename in files:
            filepath = os.path.join(root, filename)
            if is_image_file(filepath):
                image = Image.open(filepath)
                resized_image = resize_image(image)

		# 限定正方圖為2250x2250
                canvas = Image.new("RGB", (2250, 2250), (255, 255, 255))
                paste_x = (2250 - resized_image.width) // 2
                paste_y = (2250 - resized_image.height) // 2
                canvas.paste(resized_image, (paste_x, paste_y))
                canvas.save(filepath, "JPEG")

		# 圖像處理進度...

                processed_images += 1
                print(f"處理進度:{processed_images}/{total_images}")


def resize_image(image):
    width, height = image.size
    max_dimension = max(width, height)

    if max_dimension <= 2250:
        return image
    
    if width > height:
        new_width = 2250
        ratio = new_width / width
        new_height = int(height * ratio)
    else:
        new_height = 2250
        ratio = new_height / height
        new_width = int(width * ratio)

    return image.resize((new_width, new_height))

def is_image_file(filename):
    supported_extensions = [".jpg", ".jpeg", ".png", ".gif"]
    file_extension = os.path.splitext(filename)[1].lower()
    
    return file_extension in supported_extensions

# 指定代文件所在位置的文件夾裡(可以是代码文件位置的文件夹或任何其他文件夹)
folder = os.path.dirname(os.path.abspath(__file__))

# 調用函數誰行圖像處理
process_images(folder)

以下为查问ChatGPT的过程

如想一键执行,可以复制下段代码,保存为bat文件就可 (此文件名可以任改, 但Python文件必须改为autosize.py对应下方码里名字.

@echo off
python autosize.py
pause

发表回复

3
AI智能助手
WhatsApp
电子邮件
AI智能助手
WhatsApp
电子邮件
AI智能助手
重要声明:AI的响应速度可能较慢。AI提供的信息仅供参考,本公司对其准确性或完整性不承担任何责任。AI回复不代表本公司立场。

欢迎!我在这里为您解答关于 的任何问题。

02:09