Error with PHP image resizer "The connection to the server was reset while the page was loading."

70 views Asked by At

I want to use PHP to resize my images. This is my code, but when I launch it, Firefox gives error saying that:

The connection to the server was reset while the page was loading.

Why doesn't it work? Where does the error come from?

function resize_image($filename, $newwidth, $newheight){
    list($width, $height) = getimagesize($filename);
    if($width > $height && $newheight < $height){
        $newheight = $height / ($width / $newwidth);
    } else if ($width < $height && $newwidth < $width) {
        $newwidth = $width / ($height / $newheight);   
    } else {
        $newwidth = $width;
        $newheight = $height;
    }
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    $source = imagecreatefromjpeg($filename);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return imagejpeg($thumb);
}

And HTML:

<img class="top_logo" src="<?php echo resize_image('images/top_logo.png' , '100' , '100'); ?>" alt="logo"/>
1

There are 1 answers

2
Hassaan Salik On BEST ANSWER

The error you've mentioned might be caused by some infinite loop in some other part of your script. However i have corrected your code.

Remember imagecreatefromjpeg() accepts only jpeg files

<?php
    function resize_image($filename, $newwidth, $newheight)
    {
        list($width, $height) = getimagesize($filename);
        if($width > $height && $newheight < $height){
            $newheight = $height / ($width / $newwidth);
        } else if ($width < $height && $newwidth < $width) {
            $newwidth = $width / ($height / $newheight);   
        } else {
            $newwidth = $width;
            $newheight = $height;
        }
        $thumb = imagecreatetruecolor($newwidth, $newheight);
        $source = imagecreatefromjpeg($filename);
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        ob_start();
        imagejpeg($thumb);
        return 'data:image/gif;base64,' . base64_encode(ob_get_clean());
    }

    ?>
    <img class="top_logo" src="<?php echo resize_image('logo.jpeg' , '100' , '100'); ?>" alt="logo"/>