I'm writing a script that will upload a file from user input, resize it to a thumbnail and add the two new filenames to a database.
However, I cannot for the life of me figure out how to get PHP to detect the image's MIME type and then give it to the header. Here is the code, I've put comments to try and make it as clear as possible:
$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.'; }
So here is the part that I do not understand: the code works fine for when I upload a .jpeg, but if it is a PNG or a GIF, it brings up a page that says, 'The image '127.0.0.1:8888' cannot be displayed because it contains errors.' I'm supposing it must not have the correct Header MIME type, but could it be something else?
When I select a .jpeg, it uploads just fine to my image folder and it generates a thumbnail to my Thumbnail folder like I want it to.
But as soon as I try it with PNG and GIF, it fails. I must be missing something obvious?
Is this code any good for what I'm trying to accomplish?
Thanks in advance,