手搓python实现图片压缩,减小图片大小

from PIL import Image
import os
import io


def resize_image(image_path, max_size_mb):
    """
    Resize an image to ensure its size is below the given max size in megabytes.
    """
    max_size = max_size_mb * 1024 * 1024  # Convert MB to bytes
    with Image.open(image_path) as img:
        img_format = img.format if img.format else 'JPEG'  # Default to JPEG if format is None
        quality = 95

        while True:
            buffer = io.BytesIO()
            print('ok')
            img.save(buffer, format=img_format, quality=quality)
            buffer_size = len(buffer.getvalue())
            print(buffer_size)
            if buffer_size <= max_size:
                print(len(buffer.getvalue()))
                buffer.seek(0)
                x = Image.open(buffer)
                print('-'*10)
                return x
            quality -= 5
            if quality < 10:
                break

        # If the loop ends, return the lowest acceptable quality
        print('ok')
        buffer.seek(0)
        return Image.open(buffer)


def process_images(input_folder, output_folder, max_size_mb):
    """
    Process images from the input folder, resize them to ensure their size
    does not exceed max_size_mb, and save them to the output folder.
    """
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    for file_name in os.listdir(input_folder):
        if file_name.lower().endswith(('.png', '.jpg', '.jpeg')):
            input_path = os.path.join(input_folder, file_name)
            # try:

            img = resize_image(input_path, max_size_mb)
            print(img)
            output_path = os.path.join(output_folder, file_name)
            print(output_path)
            img.save(output_path)
            print(f"Processed and saved {file_name} to {output_folder}")
            # except Exception as e:
            #     print(f"Failed to process {file_name}: {e}")
# Example usage
input_folder = r'C:\Users\Administrator\Desktop\sim产品图'  # Replace with your input folder path
output_folder = r'C:\Users\Administrator\Desktop\sim产品图_out'  # Replace with your output folder path
max_size_mb = 3  # Maximum size in MB

process_images(input_folder, output_folder, max_size_mb)

上传某些图片空间的时候,出现了限制大小,写个代码 限制大小不要超过3mb

打包成了可执行文件,方便调用


https://download.csdn.net/download/m0_38124502/89677525

也可+【qq】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值