PHP implements the code that extracts an image file and displays it in the browser

  • 2020-05-24 05:18:30
  • OfStack

Last year, I did a project to make a text list of image files uploaded by users. When the user clicks on a file name, the image can be displayed.

Considering the compatibility with various image formats, I used the GD library to determine the specific image file (MINE), and then called the corresponding image generation function imagecreatefromXXX() to generate an img, and then output this img to the browser in jpeg format. Although I made it, I always felt dissatisfied.

Today, I have the opportunity to reconsider this functionality. I found a few lines of code in the php manual, which is clean and clean, and fully capable of doing what I want without the need for the GD library

 
<?php 
$size = getimagesize($filename); // To obtain mime information  
$fp=fopen($filename, "rb"); //2 Open file in base mode  
if ($size && $fp) { 
header("Content-type: {$size['mime']}"); 
fpassthru($fp); //  Output to the browser  
exit; 
} else { 
// error 
} 
?> 


The amount of code is less than a tenth of what I used to be, which is N times faster.

Related articles: