.htaccess 通过URL动态更改图像大小

hl0ma9xz  于 6个月前  发布在  其他
关注(0)|答案(2)|浏览(42)

我有一个名为images的文件夹,在那里我有像图像:hero.jpg,hero_medium.jpg,hero_small.jpg.我的问题是,如果这是正确的解决方案,或者也许它会更好地有一个大的图片,并通过URL更改其大小.目前我已经设法在images文件夹中的img.php文件中做这样的事情:

<?php
header('Content-Type: image/jpeg');
$filename = 'hero.jpg';

list($width_orig, $height_orig) = getimagesize($filename);

if(empty($_GET['w'])){
    $width = $width_orig;
} else {
    $width = $_GET['w'];
}
$height=$width;

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

imagejpeg($image_p, null, 100);

字符串
我想通过一个友好的URL来更改照片的大小,例如在php中使用htaccess将hero_medium.jpg更改为768px,这样的事情可能吗?
编辑:苹果在其网站上有一个有趣的情况.图像的URL看起来像下面这样:https://www.apple.com/newsroom/images/environments/stores/Apple_Tower-Theatre-now-open-in-downtown-LA-store-interior-wide-shot_062421_big.jpg.medium.jpg,为什么有big.jpg.medium.jpg?我怀疑他们可能是做一些与htaccess文件,因为有那么多的照片将无法读取,所以我认为他们是动态地重新定位它们.你怎么看?
编辑2:我注意到通过php加载和更改图像需要更长的时间,这真的是一个好主意吗?

hts6caw3

hts6caw31#

您想使用URL参数设置图像的宽度和高度。这对于动态浏览图像很有用。要实现这一点,您可以将宽度和高度参数附加到图像URL。下面是如何执行此操作的示例
Original Image URL:https://example.com/image.jpg
使用URL调整图片大小:https://example.com/image.jpg?width=600&height=400
HTML文件

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Image Resizing</title>
</head>
<body>
    <img src="resize.php?width=600&height=400" alt="Resized Image">
</body>
</html>

字符串
PHP文件名与'resize.php'

// Get the image file path (replace with your image's actual path)
$imagePath = 'image.png';

// Get the requested width and height from the URL parameters
$width = isset($_GET['width']) ? intval($_GET['width']) : null;
$height = isset($_GET['height']) ? intval($_GET['height']) : null;

// Check if both width and height are provided and are valid integers
if ($width && $height && is_numeric($width) && is_numeric($height)) {
    // Load the original image
    $originalImage = imagecreatefrompng($imagePath);

    // Create a new image with the specified width and height
    $resizedImage = imagecreatetruecolor($width, $height);

    // Resize the original image to the new dimensions
    imagecopyresampled($resizedImage, $originalImage, 0, 0, 0, 0, $width, $height, imagesx($originalImage), imagesy($originalImage));

    // Output the resized image as a JPEG
    header('Content-Type: image/jpeg');
    imagepng($resizedImage);

    // Clean up resources
    imagedestroy($originalImage);
    imagedestroy($resizedImage);
} else {
    // Handle the case where width and height parameters are missing or invalid
    echo 'Invalid parameters';
}

8ulbf1ek

8ulbf1ek2#

如果你只是想返回一个足够尺寸的图像,有几种方法可以实现这一点。
也许你想看看这个:https://css-tricks.com/a-guide-to-the-responsive-images-syntax-in-html/

相关问题