| Current Path : /var/www/magento.test.indacotrentino.com/www/pub/images/ |
| Current File : /var/www/magento.test.indacotrentino.com/www/pub/images/resize.php |
<?php
$validSizes = [
['width' => 1000],
['height' => 1000],
['width' => 1000, 'height' => 667],
['width' => 500],
['width' => 300]
];
function isValidSize($width, $height, $validSizes) {
foreach ($validSizes as $size) {
if (isset($size['width']) && isset($size['height'])) {
if ($size['width'] == $width && $size['height'] == $height) {
return true;
}
} elseif (isset($size['width']) && $size['width'] == $width) {
return true;
} elseif (isset($size['height']) && $size['height'] == $height) {
return true;
}
}
return false;
}
$imageName = isset($_GET['image']) ? $_GET['image'] : null;
$widthParameter = isset($_GET['width']) ? intval($_GET['width']) : null;
$heightParameter = isset($_GET['height']) ? intval($_GET['height']) : null;
$crop = false;
if (substr($_GET['width'], -1) === 'c') {
$crop = true;
}
if (substr($_GET['height'], -1) === 'c') {
$crop = true;
}
$width = $widthParameter;
$height = $heightParameter;
$firstChar = substr($imageName, 0, 1);
$secondChar = substr($imageName, 1, 1);
$imagePath = __DIR__ . "/../media/catalog/product/$firstChar/$secondChar/$imageName";
if (!file_exists($imagePath)) {
header('HTTP/1.1 404 Not Found');
echo 'Image not found.';
exit;
}
if (!$width && !$height) {
header('Content-Type: image/jpeg');
readfile($imagePath);
exit;
}
$cacheDir = __DIR__ . "/cache/$firstChar/$secondChar";
$cacheFileName = pathinfo($imageName, PATHINFO_FILENAME) . ($widthParameter ? "_{$widthParameter}" : '') . ($heightParameter ? "x{$heightParameter}" : '') . ($crop ? 'c' : '') . '.' . pathinfo($imageName, PATHINFO_EXTENSION);
$cacheFile = "$cacheDir/$cacheFileName";
if (file_exists($cacheFile)) {
header('Content-Type: image/jpeg');
readfile($cacheFile);
exit;
}
list($originalWidth, $originalHeight) = getimagesize($imagePath);
if ($width && !$height) {
$height = intval($originalHeight * ($width / $originalWidth));
} elseif ($height && !$width) {
$width = intval($originalWidth * ($height / $originalHeight));
}
if ($width > $originalWidth || $height > $originalHeight) {
$width = $originalWidth;
$height = $originalHeight;
}
isValidSize($width, $height, $validSizes);
if (!isValidSize($width, $height, $validSizes)) {
header('HTTP/1.1 400 Bad Request');
echo 'Invalid size combination.';
exit;
}
if (!file_exists($cacheDir)) {
mkdir($cacheDir, 0755, true);
}
$cmd = "convert $imagePath";
if ($crop) {
$cmd .= " -resize {$width}x{$height}^ -gravity center -extent {$width}x{$height}+0+0 +repage";
} else {
$cmd .= " -resize {$width}x{$height}";
}
$cmd .= " $cacheFile";
exec($cmd, $output, $returnVar);
if ($returnVar !== 0) {
header('HTTP/1.1 500 Internal Server Error');
echo 'Error resizing the image.';
exit;
}
header('Content-Type: image/jpeg');
readfile($cacheFile);
?>