from PIL import Image def compress_image(input_image_path, output_image_path, target_width, target_height): """ 压缩图片到指定尺寸。 :param input_image_path: 原始图片的路径 :param output_image_path: 压缩后图片的保存路径 :param target_width: 目标宽度 :param target_height: 目标高度 """ # 打开原始图片 original_image = Image.open(input_image_path) # 获取原始图片的尺寸 original_width, original_height = original_image.size # 计算压缩比例 width_ratio = target_width / original_width height_ratio = target_height / original_height # 确定使用哪个比例进行压缩,避免图片失真 ratio = min(width_ratio, height_ratio) # 计算新的尺寸 new_width = int(original_width * ratio) new_height = int(original_height * ratio) # 压缩图片 compressed_image = original_image.resize((new_width, new_height), Image.LANCZOS) # Use LANCZOS or Resampling.LANCZOS instead. # 保存压缩后的图片 compressed_image.save(output_image_path) # 使用方法 input_path = '1.jpg' # 原始图片路径 output_path = '2.jpg' # 压缩后图片保存路径 target_width = 320 # 目标宽度 target_height = 240 # 目标高度 compress_image(input_path, output_path, target_width, target_height)
标签:target,python,压缩,original,height,width,尺寸,path,image From: https://www.cnblogs.com/flyingsir/p/18052057