无法显示图像,因为它包含错误(帮助)

时间:2015-09-16 12:27:27

标签: php

<?php
// Checks if the form was submitted
if ($_SERVER ['REQUEST_METHOD'] == 'POST') {
// Checks if a file was uploaded without errors
if (isset($_FILES['photo']) && is_uploaded_file($_FILES['photo']['tmp_name'])
 && $_FILES ['photo'] ['error'] == UPLOAD_ERR_OK) {
    echo $_FILES['photo']['type'], "<br />";
    // Checks if the file is a JPG image
    if ($_FILES ['photo'] ['type'] == 'image/jpeg') {
        $tmp_img = $_FILES ['photo'] ['tmp_name'];
        // Creates an image resource
        $image = imagecreatefromjpeg ( $tmp_img );
        // Tells the browser what type of file
        header ( 'Content-Type: image/jpeg' );
        // Outputs the file to the browser
        imagejpeg ( $image, '', 90 );
        // Frees the memory used for the file
        imagedestroy ( $image );
    }
    else {
        echo "Uploaded file was not a JPG image.";
    }
} else {
    echo "No photo uploaded!";
}
} else {
// If the form was not submitted, displays the form HTML
?>
<form action="test.php" method="post"
enctype="multipart/form-data">
<label for="photo">User Photo:</label>
    <input type="file" name="photo" />
    <input type="submit" value="Upload a Photo" />
</form>
<?php } // End else statement ?>

此代码来自本书&#34; PHP for Absolute Beginners(2009).pdf&#34;,但是当我测试它时,我在Firefox中遇到以下错误:

  

无法显示图像,因为它包含错误

我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:0)

您对imagejpeg的调用是尝试将图像写入具有空路径(第二个参数)的文件,而不是在浏览器中显示,因此您需要将此参数设置为&#34; null& #34;代替。

您需要将代码更改为:

// Set second param to "null" to directly output the image
imagejpeg ( $image, null, 90 );
imagedestroy ( $image );
// Exit here so that the HTML below is not mixed with the image data:
die();