laravel12_start/public/img-handler.php

72 lines
2.2 KiB
PHP

<?php
require __DIR__ . '/../vendor/autoload.php';
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
$request = $_GET['img'];
$pathInfo = pathinfo($request);
$fileNameSegments = explode('_', $pathInfo['filename']);
$prefix = $fileNameSegments[0];
$fileName = $fileNameSegments[1] . '.' . $pathInfo['extension'];
$postFix = $fileNameSegments[2] ?? '';
$isStub = false;
$srcFile = __DIR__ . '/../storage/uploads/files-browser/' . $pathInfo['dirname'] . '/' . $fileName;
if (!file_exists($srcFile)) {
$fileName = 'no-image.jpg';
$isStub = true;
}
function resizeImg($targetWidth, $targetHeight, $filePath)
{
$d = new Driver();
$image = (new ImageManager($d))->read($filePath);
// Получение размеров исходного изображения
$originalWidth = $image->width();
$originalHeight = $image->height();
// Вычисление центральной обрезки
if ($originalWidth / $originalHeight > $targetWidth / $targetHeight) {
// Изображение слишком широкое — обрезаем ширину
$newWidth = floor($originalHeight * ($targetWidth / $targetHeight));
$newHeight = $originalHeight;
$x = floor(($originalWidth - $newWidth) / 2);
$y = 0; // Верхняя граница
} else {
// Изображение слишком высокое — обрезаем высоту
$newWidth = $originalWidth;
$newHeight = floor($originalWidth * ($targetHeight / $targetWidth));
$x = 0; // Левая граница
$y = floor(($originalHeight - $newHeight) / 2);
}
// Обрезка изображения
$image->crop($newWidth, $newHeight, $x, $y);
// Изменение размера до нужных параметров
$image->resize($targetWidth, $targetHeight);
return $image;
}
$result = null;
if (preg_match('/^(\d*)x(\d*)$/', $prefix, $matches)) {
//ресайзим
$width = $matches[1];
$height = $matches[2];
$img = resizeImg($width, $height, $srcFile);
$result = $img;
}
if ($result) {
header('Content-type: image/png');
header('Cache-Control: private, max-age=600000');
echo $result->toJpeg();
}