You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
import os
from PIL import Image
# 对图片进行压缩,实测JPG图片, 从100%到85%,体积从159K压缩到75K效果明显, 但PNG图片, 从739K压缩到729K, 基本无变化
def compress_img ( source , target ) :
cmd = ' " C: \\ Program Files \\ ImageMagick-7.1.1-Q16 \\ magick.exe " ' + source + ' -quality 85 ' + target
os . system ( cmd )
# 获取竖版4: 3的图像
def get4to3img ( filename , out ) :
# 打开图片
img = Image . open ( filename )
# 获取原始尺寸
original_width , original_height = img . size
# 目标高宽比
target_ratio = 4 / 3
# 计算目标高度, 使得高度是宽度的4/3倍
target_height = int ( original_width * target_ratio )
# 如果原始高度小于目标高度,需要在顶部和底部添加空间
if original_height < target_height :
# 创建一个新的画布,高度为目标高度,宽度保持不变
new_img = Image . new ( ' RGB ' , ( original_width , target_height ) , ' white ' )
# 计算附加空间的位置
pad_top = ( target_height - original_height ) / / 2
# 将原始图片粘贴到新画布的中心
new_img . paste ( img , ( 0 , pad_top ) )
img = new_img
new_img . close ( )
# 如果原始高度大于目标高度,需要裁剪图片
elif original_height > target_height :
# 计算裁剪的起始点
crop_top = ( original_height - target_height ) / / 2
crop_bottom = original_height - crop_top
# 裁剪图片
img = img . crop ( ( 0 , crop_top , original_width , crop_bottom ) )
# 保存调整后的图片
img . save ( out )
# 关闭图片,释放内存
img . close ( )
if __name__ == ' __main__ ' :
# 图片路径
filename = r ' D: \ backup \ 021d1281-9d0b-3acf-fc8b-1b86ff6e9832.jpg '
get43img ( filename , r ' D: \ backup \ 021d1281-9d0b-3acf-fc8b-1b86ff6e9832_222.jpg ' )