裁剪图片(直接覆盖原图)
from PIL import Image
import osdef resize_image_by_ratio(image_path, target_width=None, target_height=None, ratio=None):"""按照指定的比例或尺寸裁剪图片。:param image_path: 输入图片的路径:param output_path: 输出图片的路径:param target_width: 目标宽度,如果为None,则根据ratio计算:param target_height: 目标高度,如果为None,则根据ratio计算:param ratio: 缩放比例,如果target_width和target_height都为None,则必须提供ratio"""with Image.open(image_path) as img:width, height = img.sizeif target_width is None and target_height is None and ratio is not None:target_width = int(width * ratio)target_height = int(height * ratio)elif target_width is not None and target_height is None:target_height = int((target_width / width) * height)elif target_width is None and target_height is not None:target_width = int((target_height / height) * width)resized_img = img.resize((target_width, target_height))resized_img.save(image_path)
压缩图片
def resize_and_compress_to_size(image_path, target_size_bytes):"""尝试调整图片大小并压缩至接近指定的字节数。:param image_path: 输入图片的路径:param target_size_bytes: 目标文件大小,以字节为单位"""with Image.open(image_path) as img:original_format = img.formatquality = 95 step = 5 img.thumbnail(img.size) while True:print("quality================", quality)temp_file = f"{image_path}.temp"img.save(temp_file, format=original_format, quality=quality)file_size = os.path.getsize(temp_file)if file_size > target_size_bytes:quality -= stepif quality <= 0:break elif file_size <= target_size_bytes:breakos.remove(temp_file)img.save(image_path, format=original_format, quality=quality)
def resize_and_compress_images_in_dir(directory, target_size_bytes=None, target_width=None, target_height=None,ratio=None):"""处理指定目录下的所有图片,可以按比例缩放或压缩至指定大小。:param directory: 包含图片的目录路径:param target_size_bytes: 目标文件大小,以字节为单位,用于压缩:param target_width: 目标宽度,用于缩放:param target_height: 目标高度,用于缩放:param ratio: 缩放比例,用于缩放"""for filename in os.listdir(directory):if filename.lower().endswith(('.jpg', '.jpeg', '.png')):image_path = os.path.join(directory, filename)if target_size_bytes is not None and target_width is not None:resize_and_compress_to_size(image_path, target_size_bytes)resize_image_by_ratio(image_path, target_width=target_width, target_height=target_height, ratio=ratio)image_path = "D:\jingdong\定金_【诚邀试驾】_阿维塔_11_鸿蒙版_情感智能电动SUV_试驾享50元E卡【图片_价格_品牌_报价】_京东"
target_width = 280
target_heigh = 280
target_size_bytes = 29000
resize_and_compress_images_in_dir(image_path, target_size_bytes=target_size_bytes, target_width=target_width,target_height=target_heigh)