我想用PHP来调整图像大小。这是我的代码,但是当我启动它时,Firefox给出错误说:
加载页面时,与服务器的连接已重置。
为什么不起作用?错误从何而来?
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"/>