Home  >  Article  >  Backend Development  >  PHP implements direct output of images in the browser

PHP implements direct output of images in the browser

小云云
小云云Original
2018-03-20 14:44:563538browse

The easiest way to output images in the browser is of course to use the HTML img tag and directly pass in the image path or link. But sometimes we need to do some processing on the image, such as changing the image quality or size before displaying it. We can use PHP's built-in image processing function imagecreatefromjpeg (or imagecreatefrompng) to create a new image and imagejpeg (or imagepng) from a file or URL. ), sending Content-type: image/jpeg through header() can cause the PHP script to directly output JPEG images.

/*
 * php 页面直接输出图片
 */
function showImg($img){
	$info = getimagesize($img);
	$imgExt = image_type_to_extension($info[2], false);  //获取文件后缀
	$fun = "imagecreatefrom{$imgExt}";
	$imgInfo = $fun($img); 					//1.由文件或 URL 创建一个新图象。如:imagecreatefrompng ( string $filename )
	//$mime = $info['mime'];
	$mime = image_type_to_mime_type(exif_imagetype($img)); //获取图片的 MIME 类型
	header('Content-Type:'.$mime);
	$quality = 100;
	if($imgExt == 'png') $quality = 9;		//输出质量,JPEG格式(0-100),PNG格式(0-9)
	$getImgInfo = "image{$imgExt}";
	$getImgInfo($imgInfo, null, $quality);	//2.将图像输出到浏览器或文件。如: imagepng ( resource $image )
	imagedestroy($imgInfo);
}

Can read local image files and remote image links.
Note: imagejpeg (or imagepng) support is only available when PHP is compiled with GD-1.8 or higher. quality is optional, jpeg ranges from 0 (worst quality, smaller file size) to 100 (best quality, largest file size), and png ranges from 0 to 9.

Related recommendations:

PHP method to directly output images in the browser

The above is the detailed content of PHP implements direct output of images in the browser. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn