[Python] 纯文本查看 复制代码import os
from PIL import Image
def resize_image(input_image_path, output_image_path, max_size=1024):
img = Image.open(input_image_path)
if img.mode == 'RGBA':
img = img.convert('RGB')
if os.path.getsize(input_image_path) > max_size * 1024:
quality = 90
img.save(output_image_path, "JPEG", quality=quality)
while os.path.getsize(output_image_path) > max_size * 1024:
quality -= 5
img.save(output_image_path, "JPEG", quality=quality)
else:
img.save(output_image_path)
def resize_images_in_folder(folder_path, max_size=1024):
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith(".png"):
input_image_path = os.path.join(root, file)
output_image_path = input_image_path
resize_image(input_image_path, output_image_path, max_size)
folder_path = 'D:/a'
resize_images_in_folder(folder_path)
[i]
把小于1M的常见格式图片变成1M以上的图片[Python] 纯文本查看 复制代码import os
from PIL import Image
import io
def resize_image_to_exceed_1mb(image_path):
# 打开图片
with Image.open(image_path) as img:
# 转换为字节流
byte_arr = io.BytesIO()
img.save(byte_arr, format=img.format)
# 获取当前图片大小(字节)
size_in_bytes = len(byte_arr.getvalue())
# 转换为MB
size_in_mb = size_in_bytes / (1024 * 1024)
# 如果图片小于1MB,则调整大小
if size_in_mb