我正在编写一个脚本,它将从用户输入上传文件,将其调整为缩略图并将两个新文件名添加到数据库中。
但是,我终生无法弄清楚如何让 PHP 检测图像的 MIME 类型,然后将其提供给标题。这是代码,我已经添加了注释以尝试使其尽可能清晰:
$picture = $_FILES['picture']['name'];
/*original file location*/
$file = 'picture/'.$picture.'';
/*save thumbnail location*/
$save = 'thumb/tn-'.$picture.'';
/*append thumbnail filename with tn-*/
$thumb = 'tn-'.$picture.'';
/*get original file size*/
list($width, $height) = getimagesize($file);
/*get image MIME type*/
$size = getimagesize($file);
$fp = fopen($file, "r");
if ($size && $fp)
{
header("Content-type:".$size['mime']);
fpassthru($fp);
exit;
}
else
{
echo 'Error getting filetype.';
}
/*define thumbnail dimensions*/
$modwidth = 300;
$modheight = 200;
/*check to see if original file is not too small*/
if (($width > 301) || ($height > 201))
{
/*create shell for the thumbnail*/
$tn = imagecreatetruecolor($modwidth, $modheight);
/*HERE IS WHERE I HAVE TROUBLE*/
/*if MIME type is PNG*/
if ($size['mime'] == "image/png")
{
/*try to create PNG thumbnail*/
$image = imagecreatefrompng($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagepng($tn, $save, 100);
}
/*if MIME type is JPEG*/
if ($size['mime'] == "image/jpeg")
{
$image = imagecreatefromjpeg($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagejpeg($tn, $save, 100);
}
/*if MIME type is GIF*/
if ($size['mime'] == "image/gif")
{
$image = imagecreatefromgif($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagegif($tn, $save, 100);
}
}
else { echo 'Your file is too small.'; }
所以这是我不明白的部分:当我上传 .jpeg 时,代码可以正常工作,但如果它是 PNG 或 GIF,它会弹出一个页面,上面写着“图像 '127.0.0.1:8888 '无法显示,因为它包含错误。' 我想它一定没有正确的 Header MIME 类型,但它可能是别的东西吗?
当我选择 .jpeg 时,它会很好地上传到我的图像文件夹,并会像我想要的那样为我的 Thumbnail 文件夹生成一个缩略图。
但是,一旦我尝试使用 PNG 和 GIF,它就失败了。我一定遗漏了一些明显的东西吗?
这段代码对我想要完成的事情有好处吗?
提前致谢,