Home » Programming » PHP » Php Output Image File

Output or Display an Image in the Browser from PHP

This article will show you how to output or display an image in the web browser from PHP, with a quick copy & paste code snippet.

Images in PHP

We’ve covered how to resize images in PHP using the GD library. Once an image is created, it can be saved or returned to the browser to be displayed without saving it.

Outputting/Displaying an Image in PHP without Saving it

The following PHP code snippet creates an image object and returns it without saving it:

// The header() function is used to set the HTTP header which tells the web browser what kind of response it is receiving
// This must be changed based on the image format - eg. image/jpeg or image/png
header('content-type: image/jpeg');  

// Depending on the format of the image, different functions must be used to create an image object from the file
// pathinfo() is used to determine the image type by the file extension
switch (pathinfo($image_file_path)['extension]) {
    case 'png':
        $image = imagecreatefrompng($image_file_path);
        break;
    case 'gif':
        $image = imagecreatefromgif($image_file_path);
        break;
    default:
        $image = imagecreatefromjpeg($image_file_path);
}

// Here, you could perform operations on the image - resizing, watermarking, etc before returning it

// Output the image.  The browser will know what to do with the image data because it was told what kind of data to expect with the header() function above
echo imagejpeg($image);  

// Destroy the image object to free up memory
imagedestroy($image);

The PHP GD library includes a variety of functions for manipulating and resizing images.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment