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.

53 lines
1.8 KiB

1 year ago
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)
# 获取竖版43的图像
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')