webcito / php-auto-image-resizer
描述
dev-main
2024-05-24 10:28 UTC
Requires
- php: >=8.2
- ext-imagick: *
This package is auto-updated.
Last update: 2024-09-24 11:15:33 UTC
README
一个PHP文件,可以根据屏幕宽度缩放和传递图片。
需求
您必须至少安装PHP 8.2,并启用PHP扩展ext-imagick。
准备
首先,必须在文档根目录中修改或创建HTACCESS文件。
添加以下行
<IfModule mod_rewrite.c> # Turning on the apache rewrite engine RewriteEngine On # Specifies the base URL for per-directory rewrites RewriteBase / # First rule: If the requested path is "image-resizer.php", stop processing further rules. # ^image-resizer\.php$ - is a regular expression that exactly matches "image-resizer.php" # [L] is a flag that tells mod_rewrite to stop processing the rule set RewriteRule ^image-resizer\.php$ - [L] # Second rule: If the requested URI is any(.) file that ends (anchors the end position $) # with jpeg, jpg, gif, png, or webp, rewrite the request to "/image-resizer.php" # \.(?:jpeg|jpg|gif|png|webp)$ - is a regular expression that matches jpeg, jpg, gif, png, or webp files. # /image-resizer.php is the target where the matched request will be rewritten to # [QSA,L] are flags. QSA, or 'QueryString Append', forces the rewrite engine to append # a query string part in the substitution string to the existing one. L, or 'last', # stops mod_rewrite from processing any more rules. RewriteRule \.(?:jpeg|jpg|gif|png|webp)$ /image-resizer.php [QSA,L] </IfModule>
这些行会将所有扩展名为jpeg、jpg、gif、png或webp的图片发送到名为image-resizer.php的PHP文件。PHP文件的名称可以更改,但必须在htaccess中进行相应的调整。
确保您的Web服务器启用了重写模块。以下以Apache2为例进行说明。
对于Apache2,它可能看起来像这样
sudo a2enmod rewrite
如果没有完成,请设置AllowOverride为All:Apache默认不允许.htaccess重写。编辑您的apache2.conf文件(通常位于/etc/apache2/apache2.conf),将AllowOverride None更改为AllowOverride All,对应于相应的目录。
<Directory /var/www/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>
重新启动Web服务器
sudo service apache2 restart
安装
通过composer
composer install webcito/php-auto-image-resizer dev-main composer dump-autoload
手动
将PHP类/src/ImageCache.php加载到您的项目中。
使用
在DocumentRoot中创建一个名为image-resizer.php的PHP文件
该文件的 内容可能如下所示
<?php use Webcito\ImageCache; require_once "vendor/autoload.php"; // via composer // require_once "path/to/ImageCache.php"; // or manual $options = [ "cache" => "/cache/", // the folder from documentRoot "resolution" => null, // the max screen width "breakpoints" => [1200, 992, 768, 480, 320], // the breakpoints "compressionQuality" => 85 // quality ]; new ImageCache($options);
确保在documentRoot上有足够的权限创建缓存文件夹(例如,0755)。
这应该为您的项目奠定基础。
传递最大屏幕宽度或高度
由于PHP中没有直接测量屏幕宽度的方法,我使用了JavaScript。
在每一个公共页面上,我在头部设置一个cookie,并将其传递到选项中。
<script> document.cookie = "resolution=" + Math.max(screen.width, screen.height)+"; path=/; SameSite=None"; </script>
$options = [ 'resolution' => $_COOKIE['resolution'] ?? zero ]; new ImageCache($options);
就这样!