我正在编写一个脚本,用于从用户输入中上传文件,将其重新调整为缩略图,并将两个新文件名添加到数据库中。
但是,我不能为了我的生活找出如何让PHP检测图像的MIME类型,然后将其提供给标题。这里是代码,我已经提出了评论来尝试并尽可能清楚:
$picture = $_FILES['picture']['name'];
/*original file location*/
$file = 'picture/'.$picture.'';
/*save thumbnail location*/
$save = 'thumb/'.$picture.'';
/*append thumbnail filename with tn-*/
$thumb = ''.$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,它会显示一个页面,上面写着'The image'127.0.0.1:8888 '无法显示,因为它包含错误。'我假设它不一定有正确的Header MIME类型,但它可能是别的吗?
当我选择一个.jpeg时,它会很好地上传到我的图像文件夹,并且会像我想要的那样生成缩略图文件夹的缩略图。
但只要我尝试使用PNG和GIF,它就会失败。我必须错过明显的东西?
这个代码对我所要完成的任务有好处吗?
提前致谢,