首页 > 解决方案 > 图像大小通过 URL 动态变化

问题描述

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

<?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 更改照片的大小,即使用 htaccess 在 php 中将 hero_medium.jpg 更改为 768px,这可能吗?

编辑:Apple 在其网站上有一个有趣的情况。图片的 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 加载和更改图像需要更长的时间,这实际上是个好主意吗?

标签: php.htaccessgd

解决方案


如果您只想返回足够尺寸的图像,有几种方法可以实现此目的。

也许你想看看这个: https ://css-tricks.com/a-guide-to-the-responsive-images-syntax-in-html/


推荐阅读