调整大小后显示图像

Display an image after resizing

我正在尝试使用以下函数调整大小和图像:

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

创建函数后,我尝试使用此代码在调整大小后显示图像,但它不起作用:

<?php

    $img = resize_image('../images/avatar/demo.jpg', 120, 120);

    var_dump($img); //The result is: resource(6, gd)
?>
    <img src="<?php echo $img;?>"/>

PS:包含函数没有问题

你不能那样直接输出图像。您可以:

  1. 将图像保存到磁盘并在图像标签中输入 URL。
  2. 缓冲原始数据,对其进行 base64 编码,并将其作为数据 URI 输出(如果您正在处理大图像,我不推荐这样做。)。

方法一:

<?php
$img = resize_image('../images/avatar/demo.jpg', 120, 120);
imagejpeg($img, '../images/avatar/demo-resized.jpg');
?>
<img src="<?= 'www.example.com/images/avatar/demo-resized.jpg' ?>"/>

方法二:

<?php
$img = resize_image('../images/avatar/demo.jpg', 120, 120);
ob_start();
imagejpeg($img);
$output = base64_encode(ob_get_contents());
ob_end_clean();
?>
<img src="data:image/jpeg;base64,<?= $output; ?>"/>