调整大小后显示图像 [英] Display an image after resizing

查看:86
本文介绍了调整大小后显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to resize and image with the following function:

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;
}

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

After creating the function, I am trying to display the image after resizing by using this code but it is not working:

<?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:包含该功能没有问题

PS: There is no problem with the inclusion of the function

推荐答案

您不能以这种方式直接输出图像.您可以:

You can't directly output an image that way. You can either:

  1. 将图像保存到磁盘,然后在图像标签中输入URL.
  2. 缓冲原始数据,对其进行base64编码,然后将其输出为数据URI(如果要处理大图像,我不建议这样做.)

方法1:

<?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' ?>"/>

方法2:

<?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; ?>"/>

这篇关于调整大小后显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆