1.业务背景
图片压缩前的预处理,适配手机端图片大小显示且尽可能的减少图片存储空间的占用。通过限制图片的最大宽度和最大高度来减少图片的大小。
2.核心代码
import cv2
import os
import shutil
import math
def img_compress_by_openCV(img_path_local,img_size_thresh = 300,max_height=2560,max_width=1440):
# 压缩前图片大小
img_src_size = os.path.getsize(img_path_local)/1024
# 压缩后图片保存地址
img_path_compress = "./images/opencvs_"+img_path_local.split("/")[-1]
# 若压缩前图片大小已经大小阈值img_size_thresh则跳过压缩
if(img_src_size<img_size_thresh):
print("图片大小小于"+str(img_size_thresh)+"KB,跳过压缩");
shutil.copyfile(img_path_local,img_path_compress)
else:
print("openCV压缩前图片大小:"+str(int(img_src_size))+"KB")
# 计算压缩比
img = cv2.imread(img_path_local)
heigh, width = img.shape[:2]
print("openCV压缩前图片尺寸(heigh, width)=:("+str(int(heigh))+","+str(int(width))+")")
compress_rate = min(max_height/heigh,max_width/width,1)
# 调用openCV进行图片压缩
img_compress = cv2.resize(img, (int(heigh*compress_rate), int(width*compress_rate)),interpolation=cv2.INTER_AREA) # 双三次插值
cv2.imwrite(img_path_compress, img_compress)
# 压缩后图片大小
img_compress_size = os.path.getsize(img_path_compress)/1024
print("openCV压缩后图片大小:"+str(int(img_compress_size))+"KB")
print("openCV压缩前图片尺寸(heigh, width)=:("+str(heigh*compress_rate)+","+str(int(width*compress_rate))+")")
return img_path_compress
img_path_local = "./images/1684155324391.jpg"
img_path_compress = img_compress_by_openCV(img_path_local)
- 运行结果
openCV压缩前图片大小:2219KB
openCV压缩前图片尺寸(heigh, width)=:(4000,3000)
openCV压缩后图片大小:469KB
openCV压缩前图片尺寸(heigh, width)=:(1920.0,1440)
评论 (0)