[PHP] 用程式將jpg丟給瀏覽器,Send jpg to browser ; 用CI將圖片縮圖後傳送到瀏覽器

/////////////////程式將jpg丟給瀏覽器開始/////////////////
$img_path = '/var/www/html/XXX//img/a.jpg';
//成功後吐出圖片回傳
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($img_path));
readfile($img_path);
/////////////////程式將jpg丟給瀏覽器結束/////////////////

/////////////////程式將jpg丟給瀏覽器開始/////////////////
/*load library*/
$this->load->library('image_lib');
$this->load->library('net_util');
//必須在linux上安裝gd2
$this->img['image_library'] = 'gd2';
$this->img['maintain_ratio'] = TRUE;
//縮圖使用
private function img_resize($source,$target,$width,$height,$crop=true,$img_name,$new_foler){

 list($w,$h)=getimagesize($source);
 if ($w/$width>$h/$height){
  $this->img['width'] = $w*($height/$h);
  $this->img['height'] = $height;
  $this->img['x_axis'] = ($this->img['width']-$width)/2;
  $this->img['y_axis'] = 0;

 }else{

  $this->img['width'] = $width;
  $this->img['height'] = $h*($width/$w);
  $this->img['x_axis'] = 0;
  $this->img['y_axis'] = ($this->img['height']-$height)/2;
 }
 //若目錄不存在,先用圖片名稱建立縮圖目錄
 if(!file_exists($target.'/'.$img_name)){
  $oldmask = umask(0);
  mkdir($target.'/'.$img_name, 0777);
  umask($oldmask);
 }
 /* /var/www/html/XXX/XXX/XXX/img/XXX/shrink/X/X/1/2/3/4/img_name/50x50.jpg */
 $new_target_dir = $target.'/'. $img_name.'/'.$width.'x'.$height.'.jpg';
 //設定縮圖需要的設定
 $this->img['source_image'] =  $source;
 $this->img['new_image'] = $new_target_dir;
 $this->image_lib->initialize($this->img);
 //縮圖開始
 if (!$this->image_lib->resize()){
  echo "編輯失敗,上傳檔案發生錯誤:".$this->image_lib->display_errors();
  die();
 }
 if ($crop==true){
  $this->img['maintain_ratio']=FALSE;   //不要讓長寬自動縮放

  $this->img['source_image'] =  $new_target_dir;
  $this->img['width'] = $width;
  $this->img['height'] = $height;

  $this->image_lib->initialize($this->img);
  if (!$this->image_lib->crop()){
   echo "編輯失敗,上傳檔案發生錯誤:".$this->image_lib->display_errors();
   die();
  }
 }
 $img_path = I_DOC.'/product/shrink/'.$new_foler.'/'.$img_name.'/'.$width.'x'.$height.'.jpg';
 //成功後吐出圖片回傳
 $type = 'image/jpeg';
 header('Content-Type:'.$type);
 header('Content-Length: ' . filesize($img_path));
 readfile($img_path);
}
/////////////////程式將jpg丟給瀏覽器結束/////////////////

留言

這個網誌中的熱門文章

[MySQL] schema 與資料類型優化

[翻譯] 介紹現代網路負載平衡與代理伺服器