foreword
Last night, I finally changed the red background to a blue one. I was thinking of submitting it happily, but
I found that 201KB could not be submitted... The college requires (60KB~200KB).
Compress image
# 代码参考自 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)
In png format, it can be found that the smaller the compression parameter is set, the larger the image size is.
Image format conversion
I went up and took a look, the college requires jpg format, which is really pure and pure...
I used paint to save it as a jpg image, but the result was too small, only 35KB, let 's
use python to write a png to jpg.
The quality default is 75, but the compression ratio is too large. So I turned the quality up a bit.
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)
Finally finished transferring 86KB.