使用 PHP GD 调整图像大小并保存图像。这段代码有啥问题?

Posted

技术标签:

【中文标题】使用 PHP GD 调整图像大小并保存图像。这段代码有啥问题?【英文标题】:Resizing image using PHP GD and saving the image. What's wrong with this code?使用 PHP GD 调整图像大小并保存图像。这段代码有什么问题? 【发布时间】:2014-07-31 13:46:32 【问题描述】:

我已使用此代码检测文件类型并使用相关的图像 GD 函数来调整图像大小并将图像存储在指定的文件位置。

参数定义为:原始文件位置文件类型文件名

文件类型和文件名正在从$FILES_[][] 变量中获取信息。

但是,这段代码似乎并没有生成调整大小的图像,而是很好地更新了数据库中的新文件名列。

function resize_image($file, $type, $name) 
list($width, $height) = getimagesize($file);
$newname = 'small'.$name;
  $newwidth = $w;
  $newheight = $h;

if($type == 'image/jpeg' || 'image/jpg')


$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($dst, $newname);

else if($type == 'image/gif')


 $src = imagecreatefromgif($file);
  $dst = imagecreatetruecolor($newwidth, $newheight);
 imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
 imagegif($dst, $newname);
 
 else if($type == 'image/png' || 'image/x-png')


$src = imagecreatefrompng($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($dst, $newname);
 

else
 
 die("Invalid file! Please try again!");


return $newname;
 

【问题讨论】:

【参考方案1】:

您设置了新变量:

$newwidth = $w;
$newheight = $h;

使用未在任何地方定义的 $w$h。您可能想要使用通过使用getimagesize 获得的$width$height 变量。

【讨论】:

以上是关于使用 PHP GD 调整图像大小并保存图像。这段代码有啥问题?的主要内容,如果未能解决你的问题,请参考以下文章

使用 GD 调整图像大小

PHP GD - 调整图像框架/画布的大小,但不是实际图像

PHP GD 允许的内存大小已用尽

使用gd在php中调整图像大小后的黑色背景

仅显示图像的某些部分并使用 GD 调整其大小

使用 PHP GD lib 压缩和调整图像大小不适用于 png 和 jpg 的奇怪结果