python - 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)
解决方案
推荐阅读
- php - 使用 PHP 延迟表单处理
- windows - Inno Setup 检测是否安装了 Apache
- c# - 总是调用父对话框的 OnHelp() 覆盖而不是活动子对话框的覆盖
- function - 函数的职责
- python-3.x - 如何仅从检测到的面部拍摄快照?
- c++ - 为不同用户链接位于不同路径中的库
- node.js - 在 NodeJS 中使用 JWT 进行身份验证
- .net-core - System.Runtime 4.2.1.0 构建 v2 Azure Functions 项目的 FileNotFoundException
- java - Java - 同步但允许不同线程访问一种方法
- ios - 如何以编程方式创建 UITableView