Example of how PHP directly outputs images in a browser,
This article describes how PHP can directly output images in a browser. We will share this with you for your reference. The details are as follows:
The simplest way to output images in a browser is to use the img tag of HTML to directly input the image path or link. But sometimes we need to do some processing of the image, such as changing the quality or size of the image, we can use the built-in PHP image processing function.imagecreatefromjpeg
(Orimagecreatefrompng
) Create a new image andimagejpeg
(Orimagepng
), Throughheader()
Sending Content-type: image/jpeg allows PHP scripts to directly output JPEG images.
/** Output image on php page */function showImg ($ img) {$ info = getimagesize ($ img); $ imgExt = image_type_to_extension ($ info [2], false ); // get the file suffix $ fun = "imagecreatefrom {$ imgExt}"; $ imgInfo = $ fun ($ img); // 1. creates a new image from a file or URL. For example, imagecreatefrompng (string $ filename) // $ mime = $ info ['mime ']; $ mime = image_type_to_mime_type (exif_imagetype ($ img )); // obtain the MIME Type header ('content-Type :'. $ mime); $ quality = 100; if ($ imgExt = 'png ') $ quality = 9; // output quality, JPEG format (0-100 ), PNG format (0-9) $ getImgInfo = "image {$ imgExt}"; $ getImgInfo ($ imgInfo, null, $ quality); // 2. output the image to a browser or file. For example: imagepng (resource $ image) imagedestroy ($ imgInfo );}
You can read local image files or remote image links.
Note:imagejpeg
(Orimagepng
) Support is only available when PHP is compiled with a GD-1.8 or later. Quality is optional. jpeg ranges from 0 (the worst quality, the file is smaller) to 100 (the best quality, the maximum file size), and png ranges from 0 to 9.