昨晚终于把红底换成蓝底了,刚想着兴高采烈地去提交,结果发现201KB交不了…
学院要求(60KB~200KB), 我人傻了,看了一下wps, 啊充钱才可以。
# 代码参考自 https://blog.csdn.net/weixin_34910922/article/details/117537384
import cv2
def compress_pic(origin_img_fp, save_img_fp, compression):
# IMWRITE_JPEG_QUALITY会比IMWRITE_PNG_COMPRESSION压缩比率低一些
quality = cv2.IMWRITE_JPEG_QUALITY
assert 0 <= compression <= 100, 'please make sure 0 <= compression <= 100'
if origin_img_fp.split('.')[-1] == 'png':
# 越小照片越大
quality = cv2.IMWRITE_PNG_COMPRESSION
assert 0 <= compression <= 10, 'please make sure 0 <= compression <= 10'
img = cv2.imread(origin_img_fp)
cv2.imwrite(save_img_fp.format(compression), img, [quality, compression])
print('压缩成功', save_img_fp.format(compression))
if __name__ == '__main__':
origin_img_path = 'pic/my_640_480.png'
save_img_path = 'pic/my_640_480_compression_{}.png'
compress_pic(origin_img_path, save_img_path, 8)
png格式下可以发现, compression参数设置的越小图片的大小越大。
上去一看,学院要求jpg格式,真实纯纯大冤种…
我用画图去另存为jpg图片,结果太小了,只有35KB
还是用python写个png转jpg吧。
quality 默认是75,但是压缩率太大了。所以我把quality调大了些。
from PIL import Image
im = Image.open('pic/my_640_480.png')
im = im.convert('RGB')
im.save('pic/my_640_480.jpg', quality=100)
最后转完86KB。