如何使用PHP在服务器端按比例缩小图像? [英] How to scale down an image on the server side with PHP?
问题描述
我有一些图像是从服务器提取的,而$imgUrl
保存图像的路径.
I have some images that are pulled from a server and $imgUrl
holds the path of the image.
现在,我使用<img src="<?php echo $imgUrl ?>" width="100" height="200"/>
或CSS缩小图像,但是我想在PHP中进行处理,以便将已缩放的图像提供给DOM
Right now I use <img src="<?php echo $imgUrl ?>" width="100" height="200"/>
or CSS to scale down the image, but I want to do it in PHP so that I will serve already scaled images to the DOM
有什么想法吗?
谢谢
推荐答案
此解决方案将导致在首次请求拇指时创建拇指.以后所有的请求都将获取已创建的缩略图.它正在使用 ImageMagick :
This solution will cause the thumb to be created when it is requested for the first time. All future requests will fetch the already created thumb. It is using ImageMagick:
HTML:
<img src="script.php?img=example" />
PHP(script.php):
PHP (script.php):
$width = 140;
$height = 80;
$image = $_GET['img'];
$ext = 'png';
// Check if file exists
if ( ! file_exists('/path/to/the/'.$image.'.'.$ext))
{
die('Unable to process the requested file.');
}
// Check if a thumb already exists, otherwise create a thumb
if (file_exists('/path/to/the/'.$image.'_thumb.'.$ext))
{
$img = new imagick('/path/to/the/'.$image.'_thumb.'.$ext);
}
else
{
$img = new imagick('/path/to/the/'.$image.'.'.$ext);
$img->setImageFormat($ext);
$img->scaleImage($width, 0);
$img->cropImage($width, $height, 0, 0);
$img->writeImage('/path/to/the/'.$image.'_thumb.'.$ext);
}
// Return as an image
header('Content-Type: image/'.$ext);
echo $img;
这篇关于如何使用PHP在服务器端按比例缩小图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!