W3docs

Output an Image in PHP

In PHP, you can output an image using the built-in function header() to set the content type to an image format and the readfile() function to read the image file and output its contents.

In PHP, you can output an image using the built-in function header() to set the content type to an image format and the readfile() function to read the image file and output its contents.

For example, to output a JPEG image, you can use the following code:

Example of outputting a JPEG image in PHP

header('Content-Type: image/jpeg');
readfile('path/to/image.jpg');

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can also use the function imagecreatefromjpeg to create an image from a jpeg file and then use the function imagejpeg to output it.

Example of using the function imagecreatefromjpeg() to create an image from a jpeg file and then using the function imagejpeg() to output it in PHP

$img = imagecreatefromjpeg('path/to/image.jpg');
header('Content-Type: image/jpeg');
imagejpeg($img);
imagedestroy($img);

Note: You should call header() before any output is sent to the browser, otherwise it will not work. It's also important to note that the readfile() function will read the entire file into memory, so it may not be suitable for very large images.