所以我几乎看了每个问题并尝试使用下面的PHP脚本来显示我的图像。但它不起作用。我还试图看看是否使用PHPInfo()启用了GD库,它也正常工作。我是PHP的新手,但似乎无法实现这一点。谢谢你的帮助!
编辑:点击上传文档按钮后,我收到了一张损坏的图片图标。
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_FILES['photo'])
&& is_uploaded_file($_FILES['photo']['tmp_name'])
&& $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
foreach ($_FILES['photo'] as $key => $value) {
echo "$key : $value<br />";
}
if($_FILES['photo']['type'] == 'image/jpeg') {
$tmp_img = $_FILES['photo']['tmp_name'];
$image = imagecreatefromjpeg($tmp_img);
header('Content-Type: image/jpeg');
imagejpeg($image,NULL);
imagedestroy($image);
} else {
echo "Uploaded file ewas not a jpg image.";
}
echo "no photo uploaded.";
}
}
?>
<form enctype="multipart/form-data" action="book.php" method="post">
<input type="file" name="photo">
<input type="submit" value="upload a doc">
</form>
答案 0 :(得分:0)
您可以尝试在die();
之后添加imagedestroy($image);
以防止除图像数据之外的任何其他输出。同时将imagejpeg($image,NULL);
更改为imagejpeg($image);
。
答案 1 :(得分:0)
您无法使用tmp_name
直接访问图片。首先,您应该将图像保存到服务器,之后可以使用imagecreatefromjpeg
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_FILES['photo'])
&& is_uploaded_file($_FILES['photo']['tmp_name'])
&& $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
if($_FILES['photo']['type'] == 'image/jpeg') {
$tmp_img = $_FILES['photo']['tmp_name'];
$uniq_name = uniqid().".".explode(".",$tmp_img)[1];
move_uploaded_file($_FILES['photo']['tmp_name'],$uniq_name);
$image = imagecreatefromjpeg($uniq_name);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
} else {
echo "Uploaded file ewas not a jpg image.";
}
echo "no photo uploaded.";
}
}
?>
<form enctype="multipart/form-data" action="book.php" method="post">
<input type="file" name="photo">
<input type="submit" value="upload a doc">
</form>
答案 2 :(得分:0)
我认为问题在于echo
和PHP部分之后的输出字符串(HTML代码)。删除foreach
循环并仅在HTML是新页面或出现错误时输出HTML。
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_FILES['photo'])
&& is_uploaded_file($_FILES['photo']['tmp_name'])
&& $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
if($_FILES['photo']['type'] == 'image/jpeg') {
$tmp_img = $_FILES['photo']['tmp_name'];
$image = imagecreatefromjpeg($tmp_img);
header('Content-Type: image/jpeg');
imagejpeg($image,NULL);
imagedestroy($image);
exit; // Add this to stop the program here.
} else {
echo "Uploaded file was not a jpg image.";
}
} else {
echo 'No file was sent.';
}
}
?>
<form enctype="multipart/form-data" action="book.php" method="post">
<input type="file" name="photo">
<input type="submit" value="upload a doc">
</form>
另外一件事,如果您使用记事本进行编码,请确保文件开头没有隐藏的字符。