Pat*_*cow 3 php image-processing scale image-resizing
我有一些从服务器拉出$imgUrl的图像并保存图像的路径.
现在我使用<img src="<?php echo $imgUrl ?>" width="100" height="200"/>或者CSS来缩小图像,但是我想在PHP中这样做,以便我将已经缩放的图像提供给DOM
有任何想法吗?
谢谢
此解决方案将在第一次请求时创建拇指.所有未来的请求都将获取已创建的拇指.它使用ImageMagick:
HTML:
<img src="script.php?img=example" />
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)