ユーザー入力からファイルをアップロードし、サムネイルのサイズを変更して、2 つの新しいファイル名をデータベースに追加するスクリプトを作成しています。
しかし、私は一生、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」というページが表示されます。 「エラーが含まれているため表示できません。」正しいヘッダー MIME タイプを持っていてはいけないと思いますが、それは何か他のものでしょうか?
.jpeg を選択すると、イメージ フォルダに問題なくアップロードされ、必要に応じて Thumbnail フォルダにサムネイルが生成されます。
しかし、PNG と GIF で試してみるとすぐに失敗します。明らかな何かが欠けているに違いありませんか?
このコードは、私が達成しようとしていることに適していますか?
前もって感謝します、