Output an Image in PHP

前端 未结 12 1128
萌比男神i
萌比男神i 2020-11-22 14:33

I have an image $file ( eg ../image.jpg )

which has a mime type $type

How can I output it to the browser?

相关标签:
12条回答
  • 2020-11-22 14:45
    header("Content-type: image/png"); 
    echo file_get_contents(".../image.png");
    

    The first step is retrieve the image from a particular location and then store it on to a variable for that purpose we use the function file_get_contents() with the destination as the parameter. Next we set the content type of the output page as image type using the header file. Finally we print the retrieved file using echo.

    0 讨论(0)
  • 2020-11-22 14:46

    Try this:

    <?php
      header("Content-type: image/jpeg");
      readfile("/path/to/image.jpg");
      exit(0);
    ?>
    
    0 讨论(0)
  • 2020-11-22 14:46

    You can use header to send the right Content-type :

    header('Content-Type: ' . $type);
    

    And readfile to output the content of the image :

    readfile($file);
    


    And maybe (probably not necessary, but, just in case) you'll have to send the Content-Length header too :

    header('Content-Length: ' . filesize($file));
    


    Note : make sure you don't output anything else than your image data (no white space, for instance), or it will no longer be a valid image.

    0 讨论(0)
  • 2020-11-22 14:52

    You can use finfo (PHP 5.3+) to get the right MIME type.

    $filePath = 'YOUR_FILE.XYZ';
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $contentType = finfo_file($finfo, $filePath);
    finfo_close($finfo);
    
    header('Content-Type: ' . $contentType);
    readfile($filePath);
    

    PS: You don't have to specify Content-Length, Apache will do it for you.

    0 讨论(0)
  • 2020-11-22 14:56

    If you have the liberty to configure your webserver yourself, tools like mod_xsendfile (for Apache) are considerably better than reading and printing the file in PHP. Your PHP code would look like this:

    header("Content-type: $type");
    header("X-Sendfile: $file"); # make sure $file is the full path, not relative
    exit();
    

    mod_xsendfile picks up the X-Sendfile header and sends the file to the browser itself. This can make a real difference in performance, especially for big files. Most of the proposed solutions read the whole file into memory and then print it out. That's OK for a 20kbyte image file, but if you have a 200 MByte TIFF file, you're bound to get problems.

    0 讨论(0)
  • 2020-11-22 15:02
    $file = '../image.jpg';
    $type = 'image/jpeg';
    header('Content-Type:'.$type);
    header('Content-Length: ' . filesize($file));
    readfile($file);
    
    0 讨论(0)
提交回复
热议问题