Home  >  Article  >  Backend Development  >  PHP method to implement direct output of images in the browser

PHP method to implement direct output of images in the browser

小云云
小云云Original
2018-03-16 09:59:193669browse

This article mainly introduces the method of PHP to directly output images in the browser. It analyzes the principle and related operation skills of PHP output images in the form of examples. Friends in need can refer to it. I hope it can help everyone.

The easiest way to output images in a 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) from the file or URL Create a new image and imagejpeg (or imagepng), send via header() Content-type: image/jpeg PHP scripts can be made to output JPEG images directly.


/*
 * 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:

How header() outputs image cache usage examples

PHP output image

PHP implemented browser inspection class phpstorm browser settings php simulates browser php output pictures to browse


The above is the detailed content of PHP method to implement 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