为了保障网站的访问速度,应该对网站文章中使用的配图定义一些规范:
- 格式使用
jpg而不是png - 限定最大宽度,如图片宽度小于 700px 时使用原图,否则限定宽度为700等比缩放
- 同时生成 webp 格式的图片,在支持 webp 的浏览器中返回 webp 图片
老图片可以使用以下 Python 脚本进行处理
# coding:utf-8
import os
from PIL import Image
import cv2
def resize_image(infile, outfile='', x_s=700):
"""修改图片尺寸
:param infile: 图片源文件
:param outfile: 重设尺寸文件保存地址
:param x_s: 设置的宽度
:return:
"""
im = Image.open(infile)
x, y = im.size
if x > x_s:
y_s = int(y * x_s / x)
out = im.resize((x_s, y_s), Image.ANTIALIAS)
else:
out = im
out = out.convert('RGB')
out.save(outfile, compress_level=9)
def compress(in_path, out_path, quality=100):
print('\t', out_path)
img = cv2.imread(in_path, cv2.IMREAD_UNCHANGED)
if img is None:
# raise Exception(f'read img failed: {in_path}')
print(f'read img failed: {in_path}')
return
ext = os.path.splitext(out_path)[-1].strip('.')
if ext == 'jpg':
cv2.imwrite(out_path, img, [
cv2.IMWRITE_JPEG_QUALITY, quality,
cv2.IMWRITE_JPEG_PROGRESSIVE, 1,
cv2.IMWRITE_JPEG_OPTIMIZE, 1,
])
elif ext == 'png':
cv2.imwrite(out_path, img, [
cv2.IMWRITE_PNG_COMPRESSION, 9-int(quality/100*9)
])
elif ext == 'webp':
cv2.imwrite(out_path, img, [
cv2.IMWRITE_WEBP_QUALITY, quality
])
else:
raise Exception(f'unknown file ext: {ext}')
def main():
images_paths = [
'old_images',
'old_images/images',
]
sqls = []
for images_path in images_paths:
for img_name in os.listdir(images_path):
if img_name in ['.DS_Store', 'images']:
continue
name, ext = os.path.splitext(img_name)
if len(ext) > 5:
name = img_name
ext = ''
ext = ext.lower()
if ext in ['.gif', '.jfif', '.zip', '.webp']:
continue
# 只处理以下三种格式
if ext not in ['.png', '.jpeg', '.jpg']:
print(f'ERROR: {img_name}')
continue
# 图片完整路径
full_path = os.path.join(images_path, img_name)
if not os.path.exists(f'temp/{images_path}'):
os.makedirs(f'temp/{images_path}')
if not os.path.exists(f'temp_webp/{images_path.replace("images", "webp")}'):
os.makedirs(f'temp_webp/{images_path.replace("images", "webp")}')
temp_path = f'temp/{images_path}/{name}.jpg'
# 先压缩尺寸 并且保存为jpg
resize_image(full_path, temp_path)
# 生成webp
webp_path = f'temp_webp/{images_path.replace("images", "webp")}/{name}.webp'
compress(in_path=temp_path, out_path=webp_path, quality=80)
if ext == '.png':
# png 的图片转 jpg,后续还需要修改数据库的逻辑
new_image_name = f"{name}.jpg"
sql = f'UPDATE `articles` SET `thumb` = REPLACE(`thumb`, "{img_name}", "{new_image_name}"), `background` = REPLACE(`background`, "{img_name}", "{new_image_name}"), `contents` = REPLACE(`contents`, "{img_name}", "{new_image_name}"), `update_time`=`update_time`;'
sqls.append(sql)
with open('result.sql', mode='w', encoding='utf-8') as f:
f.write("\n".join(sqls))
if __name__ == '__main__':
main()


