我有一个名为
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 更改照片的大小,即 Hero_medium.jpg 到例如使用 htaccess 在 php 中实现 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 加载和更改图像需要更长的时间,这实际上是一个好主意吗?
如果您只想返回足够尺寸的图像,有多种方法可以实现此目的。
也许你想看看这个: https://css-tricks.com/a-guide-to-the-responsive-images-syntax-in-html/
您想要使用 URL 参数设置图像的宽度和高度。这对于动态调整图像大小非常有用。为此,您可以将宽度和高度参数附加到图像 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>
带有“resize.php”的 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';
}