navt / reduction
优化网站上的图片大小
Requires
- php: >=7.2.0
- psr/log: ^1.1
This package is auto-updated.
Last update: 2024-09-22 11:59:49 UTC
README
Utility Reduction旨在优化网站上的图片大小。通常,用户上传的图片太大:)
应用程序的逻辑如下:首先,检查目录中是否存在大于一定大小的图片文件(jpeg、png、gif),然后可以找到的文件可以用最佳宽度和高度(比例保持正确)覆盖。文件会递归搜索。
您不仅可以按文件大小选择图片,还可以按图片的“长边”大小选择。设置在文件data/config.json
中。
为了了解应用程序运行的时间和消耗的内存,编写了Marker类。结果将写入日志。
让我们看一下文件data/config.json
,其中
"folderPath"
- 从app.php
到目标图片目录的相对路径
"mode"
- 选择图片的模式,可以是"ImageSide"
或"FileSize"
"maxFileSize"
- 在"FileSize"
模式下,大于指定字节的文件将被选择
"maxImageSide"
- 在"ImageSide"
模式下,长边大于此处指定的像素值的文件将被选择
"maxWidth"
- 新图片的宽度,如果图片是水平的,以像素为单位
"maxHeight"
- 新图片的高度,如果图片是垂直的,以像素为单位
"ableTypes"
- 文件扩展名数组,可选值应为3个,选择一个或两个以实现“点”功能
"quality"
- 使用imagejpeg()、imagepng()函数记录jpeg和png图片时的质量参数
用法
考虑将vendor
目录放置在您网站根目录中的情况。
# go to the root directory of site $ cd root-of-site # require package navt/reduction $ composer require navt/reduction:dev-master # make sure that there is no app.php file and no data directory in the root directory. # copy $ cp vendor/navt/reduction/app.php ./ $ cp -r vendor/navt/reduction/data ./
编辑data/config.json
和app.php
以符合您的当前任务。
运行
$ php -f app.php
最初,app.php
文件包含检查目标目录的代码。如果您决定是时候减小所选文件的大小,那么app.php
中的代码应该更改为
<?php chdir(__DIR__); require_once __DIR__.'/vendor/autoload.php'; use navt\Reduction\Logger\Logger; use navt\Reduction\Marker; use navt\Reduction\Reduction; $log = new Logger("data/app.log"); $marker = new Marker($log); // create a Reduction instance, get a list of files, print to the log $reduct = new Reduction($log, "data/config.json"); $reduct->getList(); // creates a list of filtered files $reduct->printList(); $marker->addMark(); // add timestamp // reduce the size of the files in the list, destroy the Reduction instance $reduct->reductAll(); // overwrite files $reduct = null; $marker->addMark(); // check what happened $reduct = new Reduction($log, "data/config.json"); $reduct->getList(); $reduct->printList(); $marker->addMark(); $marker->display();
特点
使用控制台更佳,因为当图片数量足够多时,应用程序完成任务的耗时较长。通过少量文件进行评估运行,了解工具的工作速度。
注意保护您的数据完整性:对您计划进行工作的目录进行备份,在本地计算机上对测试数据进行脚本运行,看看结果是否令您满意。
要处理jpeg、png和gif(非动画)图片,将使用PHP模块gd
。
要处理具有多个图层(动画)的gif图片,必须在您的服务器上安装PHP模块imagick
。如果没有这样的模块,则动画gif将不受影响。
如果您打算缩小具有多个图层的gif,请考虑单独运行仅针对gif的工具。