imagecreatefromjpeg无法正常工作

I've been trying to resize an image using php but I'm having issues getting the imagecreatefromjpeg function to work. When I try to display an image, a whole bunch of characters appear on the screen, not the image. I don't see any errors either.

So, initially I tried to resize an image using this function. A bunch of random characters were displayed so I figured I'd simplify it for debugging.

function chgSize($image, $width, $height){
    $name = $image["name"]; //this is displaying the file name correctly
    $temp = $image["tmp_name"];
    $imageContents = imagecreatefromjpeg($temp);
    $blankImage = imagecreatetruecolor(100,100);

    if(imagecopyresampled($blankImage, $imageContents, 0, 0, 0, 0, 100, 100, $width, $height)){ 
        header('Content-type: image/jpeg');
        imagejpeg($blankImage, $name); //name the image and output it

        //$this->saveImage($formattedImage); //save the image, commented out for testing purposes
    }
}

edit - I got it to work. I didn't realize the second parameter in imagejpeg was the path, not just the image's name. On PHP's website parameter 2 was shown as a name in each instance, so I assumed that's all it was.

You haven't output a content-type header to indicate to the browser that you're sending over JPEG image data. Add a

header('Content-type: image/jpeg');

immediately before your imagejpeg() call.

Have you tried using the correct header?

header('Content-Type: image/jpeg');

You should also make sure you don't output any text before this.

Sounds like you are printing out the raw data of a jpeg. I'm not sure what your intended application is but you should either:

  • Save the contents of $imgContents to a file on the server which can be served via an HTML image tag
  • Output the proper HTTP headers to instruct the browser that the file it's receiving is actually a JPG, not HTML markup or text: header('Content-Type: image/jpeg');