本帖最后由 zjg121 于 2024-4-3 11:35 编辑
把jpg、jpeg、png大图变成1M以下的图片
[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)
把小于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 < 1:
# 假设我们可以通过增加图片的宽度和高度来增大图片大小
# 你可以根据实际情况调整这个比例,这里假设我们扩大1.5倍
scale_factor = 1.5
new_width = int(img.width * scale_factor)
new_height = int(img.height * scale_factor)
# 调整图片大小
resized_img = img.resize((new_width, new_height))
# 保存调整大小后的图片并检查其大小
byte_arr = io.BytesIO()
resized_img.save(byte_arr, format=img.format)
resized_size_in_bytes = len(byte_arr.getvalue())
# 如果大小仍然小于1MB,则可能需要进一步调整大小或使用更复杂的策略
# 这里只是一个简单的示例,实际情况可能需要更复杂的处理
while resized_size_in_bytes / (1024 * 1024) < 1:
scale_factor *= 1.1
new_width = int(resized_img.width * scale_factor)
new_height = int(resized_img.height * scale_factor)
resized_img = resized_img.resize((new_width, new_height))
byte_arr = io.BytesIO()
resized_img.save(byte_arr, format=img.format)
resized_size_in_bytes = len(byte_arr.getvalue())
# 保存调整大小后的图片到原文件
resized_img.save(image_path, format=img.format)
# 指定文件夹路径
folder_path = r'D:\a\pic'
# 遍历文件夹中的所有图片文件
for filename in os.listdir(folder_path):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff')):
image_path = os.path.join(folder_path, filename)
resize_image_to_exceed_1mb(image_path)
print("处理完成!") |