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】