首页 > 解决方案 > Pil 图像裁剪正在增加图像的文件大小

问题描述

我发现如果我将网站背景图像拆分成更小的图像,我可以获得更好的 PageSpeeds 。我创建了一个 python 脚本来执行此操作,以避免每次需要更改某些内容时都需要创建 6 个副本并在预览中裁剪它们,但是裁剪的图像太大。底部的文件大小比我的原始图像大

我正在拆分的图像(154 kb)

较大的底部分割图像(160 kb)

将图像拆分为较小图像的脚本

from PIL import Image
import os
import ntpath

def crop(pathToFile, height, width=False):
    im = Image.open(pathToFile)
    imgwidth, imgheight = im.size
    [name, ext] = ntpath.basename(pathToFile).split('.')
    if(not width):
        width = imgwidth
    k=0
    for i in range(0,imgheight,height):
        for j in range(0,imgwidth,width):
            box = (j, i, j+width, i+height)
            a = im.crop(box)
            a.save(os.path.join("./" + name + str(k) + "." + ext), compress_level=9, optimize=True)
            k +=1

pathToFile = './path/to/wheat-background.jpg'
crop(pathToFile, 933)

标签: pythonimage-processingpython-imaging-librarypagespeed-insights

解决方案


推荐阅读