PHP 图像缩放器 "The connection to the server was reset while the page was loading." 出错

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

我想使用 PHP 调整我的图片大小。这是我的代码,但是当我启动它时,Firefox 给出错误提示:

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

为什么不起作用?错误从何而来?

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

和HTML:

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

您提到的错误可能是由脚本其他部分的无限循环引起的。但是我已经更正了你的代码。

记住 imagecreatefromjpeg() 只接受 jpeg 个文件

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