共计 1636 个字符,预计需要花费 5 分钟才能阅读完成。
背景
我走到哪里总喜欢拍一些风景什么的,由于拍出来的照片都在好几兆,直接放在博客上供大家访问长此以往虚拟主机的流量消耗 会上去,另外页面加载的速度也比较缓慢,所以就想到了压缩照片,试过一些在线工具,压缩完取回本地实在太慢,也试过调 tinypng 的接口来压缩,可是 tinypng 的速度比在线的还要慢就放弃了。
环境
- Linuxmint 19.2
- Python 3.6.8
- Opencv 4.1.1.26
参考
- http://eunsetee.com/bVwx
依赖
sudo pip3 install opencv-python==4.1.1.26
使用说明
usage: images_compressing.py [-h] [-d DIRNAME] [-g GALLERYNAME]
Compress the images and then print gallery statements
optional arguments:
-h, --help show this help message and exit
-d DIRNAME, --dirname DIRNAME
the directory name including the images you want to
compress
-g GALLERYNAME, --galleryname GALLERYNAME
the gallery name including the images you want to post
这里主要说一下第二个参数 -g,这个参数比如说在我的博客部署环境下是指在 source/img/gallery 文件夹下面再创建的文件夹,最终主要用来输出 gallery 的声明用的,如下:
{% gallery /img/gallery/huawei_xicun/1.jpg 华为溪村 %}
{% gallery /img/gallery/huawei_xicun/2.jpg 华为溪村 %}
gallery 和 1.jpg 之间的部分就是这个参数生成的。
代码
import os
import cv2
import argparse
def compress(dirname):
for filename in os.listdir(dirname):
img=cv2.imread(dirname+'/'+filename,1)
cv2.imwrite(dirname+'/'+filename,img,[cv2.IMWRITE_JPEG_QUALITY,20])
def print_gallery_statements(dirname, gallery_name):
for filename in os.listdir(dirname):
print("{{% gallery /img/gallery/{}/{} {} %}}".format(gallery_name,filename,dirname))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Compress the images and then print gallery statements')
parser.add_argument(
'-d', '--dirname',
type=str,
help="the directory name including the images you want to compress")
parser.add_argument(
'-g', '--galleryname',
type=str,
help="the gallery name including the images you want to post")
args = parser.parse_args()
compress(args.dirname)
print_gallery_statements(args.dirname, args.galleryname)
压缩效果
写在最后
- 如果想支持命令行更改图片压缩质量的功能或其它功能,欢迎给我发邮件到 [email protected] 付费定制哦~
正文完
发表至: Python编程
2019-10-24