Home > Backend Development > PHP Tutorial > Code sharing for php to read image content and output it to the browser

Code sharing for php to read image content and output it to the browser

WBOY
Release: 2016-07-25 08:57:11
Original
1267 people have browsed it
This article introduces how to use PHP to read images and output it to a piece of code displayed by the browser. Friends in need can refer to it.

In php, if php outputs pictures, zip, exe and other files to the browser, and other characters are output in front, garbled characters will appear. Cause Analysis: It is caused by spaces or other characters being output before the output image. Please check whether there are other characters before the output image. If it is UTF-8 encoding, remember to save it as a BOM-free file.

Example:

<?php
//输出图片内容到浏览器
//by bbs.it-home.org
class imgdata{
 public $imgsrc;
 public $imgdata;
 public $imgform;
 public function getdir($source){
  $this->imgsrc  = $source;
 }
 public function img2data(){
  $this->_imgfrom($this->imgsrc);
  return $this->imgdata=fread(fopen($this->imgsrc,'rb'),filesize($this->imgsrc));
 }
 public function data2img(){
  header("content-type:$this->imgform");
  echo $this->imgdata;
  //echo $this->imgform;
  //imagecreatefromstring($this->imgdata);
 }
 public function _imgfrom($imgsrc){
  $info=getimagesize($imgsrc);
  //var_dump($info);
  return $this->imgform = $info['mime'];
 }
}
$n = new imgdata;
$n -> getdir("1.jpg");
$n -> img2data();
$n -> data2img();
?>
Copy after login

Attached, extract an image file and display it on the browser, code:

<?php
$size = getimagesize($filename); //获取mime信息
$fp=fopen($filename, "rb"); //二进制方式打开文件
if ($size && $fp) {
header("Content-type: {$size['mime']}");
fpassthru($fp); // 输出至浏览器
exit;
} else {
// error
}
?>
Copy after login


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template