coercive/imgprocess

Coercive Utility ImgProcess

0.1.1 2024-01-26 11:21 UTC

This package is auto-updated.

Last update: 2024-09-26 12:44:54 UTC


README

  • ImgProcess 允许您使用类似 "cover" 的实用选项轻松在 PHP 中调整图像大小,该选项允许覆盖提供的尺寸区域,就像具有相同名称的 CSS 属性一样;或者 "crop" 允许您裁剪图像的特定区域。

获取

composer require coercive/imgprocess

调整图像大小

use Coercive\Utility\ImgProcess\ImgProcess;

# INIT
$img = new ImgProcess;

# QUALITY (optional : default jpg 60 /  png 0)
$img
	->setJpgQuality(50)
	->setPngCompression(5);

# EXAMPLE SET
$img
	->setOverwriting(true)
	->setInputPath('source/path/image_name.jpg')
	->setOutputPath('output/path/new_image.jpg')
	->setSourceCoordinate('RIGHT', 'BOTTOM')
	->setOutputSize(1000, 1000);

# PROCESS
$bVerif = $img->sameSize();
// or
$bVerif = $img->myOwnSize(500);
// or
$bVerif = $img->crop();
// or
$bVerif = $img->cover();
// ...

# HANDLE ERRORS
if( !$bVerif ) {
	if( $aError = $img->getError() ) {
		foreach ($aError as $sMessage) { echo "<p>$sMessage</p>"; }
		die('Shutdow After Process');
	}
	else {
		die('Shutdow After Process : Unknow Error.');
	}
}

检测图像质量

# DETECT IMAGE QUALITY (base on linux 'identify')
$iQuality = ImgProcess::getImageQuality('/path/image_name.jpg');

获取图像大小

$sizes = ImgProcess::getImageSize('/path/image_name.jpg');
echo $sizes['width'] . ' x ' . $sizes['height']

响应式 HTML 图像

重新格式化 HTML 内容的示例。

<section>
    <p>Hello World</p>
    <img src="my-image.jpg" alt="Hello World" />
</section>

实例化基本选项

use Coercive\Utility\ImgProcess\ImgResponsive;

$rii = (new ImgResponsive)
    ->overwrite(true)
    ->data($data)
    ->path('/rootpath/server/img', '/realpath/img')

带有倍数选项的 SRCSET 模式

$rii
    ->modeSrcset(true)
    ->size(500, '1x', true)
    ->size(1000, '2x')
    ->size(1500, '3x')

带有查询选项的 SRCSET 模式

$rii
    ->modeSrcset()
    ->size(645, '(max-width: 750px) 645px')
    ->size(1095, '(min-width: 751px) and (max-width: 938px) 1095px')
    ->size(862, '(min-width: 939px) and (max-width: 1169px) 832px')
    ->size(1095, '(min-width: 1170px) 1095px', true)

带有查询选项的 PICTURE 模式

$rii
    ->modePicture()
    ->size(645, '(max-width: 750px) 645px')
    ->size(1095, '(min-width: 751px) and (max-width: 938px) 1095px')
    ->size(862, '(min-width: 939px) and (max-width: 1169px) 832px')
    ->size(1095, '(min-width: 1170px) 1095px', true)

解析图像 src 路径

以下是一个示例,如果您的目录结构复杂,如何检索正确的图像路径。

$rii->resolve(function ($path) {
    $path = urldecode($path);

    if(!preg_match('`/(?P<env>testmode|production)/filedirectory/(?P<relpath>/.+)$`', $path, $matches)) {
        return '';
    }

    $env = $matches['env'];
    $relpath = $matches['relpath'];
    return  preg_replace('`testmode|production`', $env, '/root/production/specific/path') . $relpath;
});

开始处理并获取 HTML

try {
    $rii->process();
}
catch (Exception $e) {
    // do something
    echo $e->getMessage();
    exit;
}

$formattedHtml = $rii->getHtml();
if(!$formattedHtml) {
    die('KO');
}

echo $formattedHtml;