Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an image after resizing

Tags:

php

gd

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: There is no problem with the inclusion of the function

like image 716
Lei Lionel Avatar asked Mar 05 '26 02:03

Lei Lionel


1 Answers

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

  1. Save the image to disk and enter the URL in the image tag.
  2. Buffer the raw data, base64 encode it, and output it as a data URI (I wouldn't recommend this if you're working with large images.).

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

Approach 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; ?>"/>
like image 150
timclutton Avatar answered Mar 07 '26 14:03

timclutton