我正在编写一个脚本,它将从用户输入上传文件,将其调整为缩略图并将两个新文件名添加到数据库中。使用PHP GD库来调整大小和保存图像HELL
但是,我不能为我的生活弄清楚如何让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时,它会很好地上传到我的图像文件夹,它会像我想要的那样生成缩略图文件夹的缩略图。
但是,只要我尝试使用PNG和GIF,它就会失败。我必须错过明显的东西?
这段代码对我所要完成的工作有什么好处?
在此先感谢,
我冒昧编辑以降低信噪比。非常具体的信息并没有帮助这个问题。我做了投票,因为我认为这是一个有趣的问题,祝你好运! – Trufa 2011-03-10 01:17:59
我有几本关于PHP的书,我正在稳步学习。我不'坚持复制粘贴在一起',这可能是一种夸大,批准。你花了5分钟阅读代码并理解我的问题?这是在绞尽脑汁。我喜欢PHP,但我真的觉得我需要得到这样一个人的帮助,这个人比我长得多。 – Seraw 2011-03-10 01:20:34
@coreyward:我完全不同意,在他们确信他们甚至想用语言编码之前,没有人必须购买和阅读整本书,他可能将其作为一种业余爱好,现在可能不会有一个真正的项目,我都是为了书,但只有当你决心掌握一门语言!毕竟这是一个问答网站,我认为这不是一个微不足道的问题,实际上它已经付出了一些努力,而且可能很有趣。 – Trufa 2011-03-10 01:21:23