>  기사  >  백엔드 개발  >  썸네일 이미지를 생성하는 PHP 클래스

썸네일 이미지를 생성하는 PHP 클래스

墨辰丷
墨辰丷원래의
2018-06-07 14:41:241559검색

이 글은 주로 PHP로 썸네일 이미지를 생성하는 클래스를 소개합니다. 관심있는 친구들이 참고하시면 좋을 것 같습니다.

기능: jpg, jpeg, gif, png, bmp 이미지 형식 지원, 원본 이미지의 비율에 따른 크기 조정 지원, 이미지 크기 조정 프로세스 중에 이미지를 잘라야 하는지 여부를 선택할 수 있으며 이미지 품질 제어가 추가되었습니다. , 이를 달성할 수 있습니다. 썸네일 이미지 품질이 최대화됩니다. 전체 클래스의 코드는 다음과 같습니다.

<?php
/**
 * 功能:php生成缩略图片的类
 */
 class ResizeImage{
  public $type;//图片类型
  public $width;//实际宽度
  public $height;//实际高度
  public $resize_width;//改变后的宽度
  public $resize_height;//改变后的高度
  public $cut;//是否裁图
  public $srcimg;//源图象 
  public $dstimg;//目标图象地址
  public $im;//临时创建的图象
  public $quality;//图片质量
  function resizeimage($img,$wid,$hei,$c,$dstpath,$quality=100){
   $this->srcimg=$img;
   $this->resize_width=$wid;
   $this->resize_height=$hei;
   $this->cut=$c;
   $this->quality=$quality;
   $this->type=strtolower(substr(strrchr($this->srcimg,&#39;.&#39;),1));//图片的类型
   $this->initi_img();//初始化图象
   $this -> dst_img($dstpath);//目标图象地址
   @$this->width=imagesx($this->im);
   @$this->height=imagesy($this->im);
   $this->newimg();//生成图象
   @ImageDestroy($this->im);
  }
  function newimg(){
   $resize_ratio=($this->resize_width)/($this->resize_height);//改变后的图象的比例
   @$ratio=($this->width)/($this->height);//实际图象的比例
   if(($this->cut)==&#39;1&#39;){//裁图
    if($img_func===&#39;imagepng&#39;&&(str_replace(&#39;.&#39;,&#39;&#39;,PHP_VERSION)>=512)){ //针对php版本大于5.12参数变化后的处理情况
     $quality=9;
    }
    if($ratio>=$resize_ratio){//高度优先
     $newimg=imagecreatetruecolor($this->resize_width,$this->resize_height);
     imagecopyresampled($newimg,$this->im,0,0,0,0,$this->resize_width,$this->resize_height,(($this->height)*$resize_ratio),$this->height);
     imagejpeg($newimg,$this->dstimg,$this->quality);
    }
    if($ratio<$resize_ratio){//宽度优先
     $newimg=imagecreatetruecolor($this->resize_width,$this->resize_height);
     imagecopyresampled($newimg,$this->im,0,0,0,0,$this->resize_width,$this->resize_height,$this->width,(($this->width)/$resize_ratio));
     imagejpeg($newimg,$this->dstimg,$this->quality);
    }
   }else{//不裁图
    if($ratio>=$resize_ratio){
     $newimg=imagecreatetruecolor($this->resize_width,($this->resize_width)/$ratio);
     imagecopyresampled($newimg,$this->im,0,0,0,0,$this->resize_width,($this->resize_width)/$ratio,$this->width,$this->height);
     imagejpeg($newimg,$this->dstimg,$this->quality);
    }
    if($ratio<$resize_ratio){
     @$newimg=imagecreatetruecolor(($this->resize_height)*$ratio,$this->resize_height);
     @imagecopyresampled($newimg,$this->im,0,0,0,0,($this->resize_height)*$ratio,$this->resize_height,$this->width,$this->height);
     @imagejpeg($newimg,$this->dstimg,$this->quality);
    }
   }
  }
  function initi_img(){//初始化图象
   if($this->type==&#39;jpg&#39; || $this->type==&#39;jpeg&#39;){
    $this->im=imagecreatefromjpeg($this->srcimg);
   }
   if($this->type==&#39;gif&#39;){
    $this->im=imagecreatefromgif($this->srcimg);
   }
   if($this->type==&#39;png&#39;){
    $this->im=imagecreatefrompng($this->srcimg);
   }
   if($this->type==&#39;wbm&#39;){
    @$this->im=imagecreatefromwbmp($this->srcimg);
   }
   if($this->type==&#39;bmp&#39;){
    $this->im=$this->ImageCreateFromBMP($this->srcimg);
   }
  }
  function dst_img($dstpath){//图象目标地址
   $full_length=strlen($this->srcimg);
   $type_length=strlen($this->type);
   $name_length=$full_length-$type_length;
   $name=substr($this->srcimg,0,$name_length-1);
   $this->dstimg=$dstpath;
   //echo $this->dstimg;
  }
   
  function ImageCreateFromBMP($filename){ //自定义函数处理bmp图片
   if(!$f1=fopen($filename,"rb"))returnFALSE;
   $FILE=unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset",fread($f1,14));
   if($FILE[&#39;file_type&#39;]!=19778)returnFALSE;
   $BMP=unpack(&#39;Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel&#39;.
     &#39;/Vcompression/Vsize_bitmap/Vhoriz_resolution&#39;.
     &#39;/Vvert_resolution/Vcolors_used/Vcolors_important&#39;,fread($f1,40));
   $BMP[&#39;colors&#39;]=pow(2,$BMP[&#39;bits_per_pixel&#39;]);
   if($BMP[&#39;size_bitmap&#39;]==0)$BMP[&#39;size_bitmap&#39;]=$FILE[&#39;file_size&#39;]-$FILE[&#39;bitmap_offset&#39;];
   $BMP[&#39;bytes_per_pixel&#39;]=$BMP[&#39;bits_per_pixel&#39;]/8;
   $BMP[&#39;bytes_per_pixel2&#39;]=ceil($BMP[&#39;bytes_per_pixel&#39;]);
   $BMP[&#39;decal&#39;]=($BMP[&#39;width&#39;]*$BMP[&#39;bytes_per_pixel&#39;]/4);
   $BMP[&#39;decal&#39;]-=floor($BMP[&#39;width&#39;]*$BMP[&#39;bytes_per_pixel&#39;]/4);
   $BMP[&#39;decal&#39;]=4-(4*$BMP[&#39;decal&#39;]);
   if($BMP[&#39;decal&#39;]==4)$BMP[&#39;decal&#39;]=0;
   $PALETTE=array();
   if($BMP[&#39;colors&#39;]<16777216)
   {
    $PALETTE=unpack(&#39;V&#39;.$BMP[&#39;colors&#39;],fread($f1,$BMP[&#39;colors&#39;]*4));
   }
   $IMG=fread($f1,$BMP[&#39;size_bitmap&#39;]);
   $VIDE=chr(0);
   $res=imagecreatetruecolor($BMP[&#39;width&#39;],$BMP[&#39;height&#39;]);
   $P=0;
   $Y=$BMP[&#39;height&#39;]-1;
   while($Y>=0)
   {
    $X=0;
    while($X<$BMP[&#39;width&#39;])
    {
     if($BMP[&#39;bits_per_pixel&#39;]==24)
      $COLOR=unpack("V",substr($IMG,$P,3).$VIDE);
     elseif($BMP[&#39;bits_per_pixel&#39;]==16)
     {
      $COLOR=unpack("n",substr($IMG,$P,2));
      $COLOR[1]=$PALETTE[$COLOR[1]+1];
     }
     elseif($BMP[&#39;bits_per_pixel&#39;]==8)
     {
      $COLOR=unpack("n",$VIDE.substr($IMG,$P,1));
      $COLOR[1]=$PALETTE[$COLOR[1]+1];
     }
     elseif($BMP[&#39;bits_per_pixel&#39;]==4)
     {
      $COLOR=unpack("n",$VIDE.substr($IMG,floor($P),1));
      if(($P*2)%2==0)$COLOR[1]=($COLOR[1]>>4);else$COLOR[1]=($COLOR[1]&0x0F);
      $COLOR[1]=$PALETTE[$COLOR[1]+1];
     }
     elseif($BMP[&#39;bits_per_pixel&#39;]==1)
     {
      $COLOR=unpack("n",$VIDE.substr($IMG,floor($P),1));
      if(($P*8)%8==0)$COLOR[1]=$COLOR[1]>>7;
      elseif(($P*8)%8==1)$COLOR[1]=($COLOR[1]&0x40)>>6;
      elseif(($P*8)%8==2)$COLOR[1]=($COLOR[1]&0x20)>>5;
      elseif(($P*8)%8==3)$COLOR[1]=($COLOR[1]&0x10)>>4;
      elseif(($P*8)%8==4)$COLOR[1]=($COLOR[1]&0x8)>>3;
      elseif(($P*8)%8==5)$COLOR[1]=($COLOR[1]&0x4)>>2;
      elseif(($P*8)%8==6)$COLOR[1]=($COLOR[1]&0x2)>>1;
      elseif(($P*8)%8==7)$COLOR[1]=($COLOR[1]&0x1);
      $COLOR[1]=$PALETTE[$COLOR[1]+1];
     }
     else
      returnFALSE;
     imagesetpixel($res,$X,$Y,$COLOR[1]);
     $X++;
     $P+=$BMP[&#39;bytes_per_pixel&#39;];
    }
    $Y--;
    $P+=$BMP[&#39;decal&#39;];
   }
   fclose($f1);
   return$res;
  }
   
 }
?>

사용 방법은 매우 간단합니다. 코드는 다음과 같습니다.

$resizeimage=new ResizeImage(&#39;upload/abc.bmp&#39;, &#39;120&#39;, &#39;90&#39;, &#39;0&#39;, &#39;upload/xabc.bmp&#39;);


또 다른 강력한 PHP 이미지 썸네일 클래스: phpThumb

이미지 크기 조정 외에도 이 클래스는 이미지를 다른 형식 출력으로 변환할 수도 있습니다(예: GIF 형식 사진을 PNG 형식으로 내보내기). 특수 기능에는 색상, 특수 효과 등도 포함됩니다.

공식 웹사이트: http://phpthumb.sourceforge.net/

우리는 오픈 소스 PHP 스크립트인 phpThumb을 사용하여 즉석에서 썸네일을 생성할 것입니다.

phpThumb을 다운로드하여 웹사이트 폴더 어딘가에 추출하세요. 이제 이미지의 둥근 모서리 썸네일을 사용하려면 다음과 같이 HTML의 img 태그를 사용하세요. src as

 <img src=”phpThumb.php?src=test.jpg&w=200&h=150&fltr[]=ric|20|20&f=png” /> 

 Adjust the path to phpThumb according to where you place the phpThumb files.

 <html> 
 <head>
 </head> 
 <body> 
  <img src="phpThumb/phpThumb.php?src=../images/test.jpg&w=400&fltr[]=fram|3|2|CC9966|333333|CCCCCC" alt=""> 
 </body> 
 </html>

일반적으로 다음 파일이면 충분합니다

사실 phpThumb은 제가 원래 생각했던 것보다 더 강력합니다. 다른 유용한 매개변수를 나열해 보겠습니다.

src: 대상 이미지의 주소

w: 출력 이미지의 너비

h: 출력 이미지의 높이(지정하지 않으면 w 매개변수에 따라 비례적으로 크기가 조정됩니다.)

q: 출력이 JPG 형식인 경우 출력 품질을 지정할 수 있습니다.

bg: 출력 중 배경(필요한 경우)

sw, sh, sx, sy: 로컬 출력, 너비, 높이, 시작 위치

f: 출력 형식(jpeg, png, gif, ico

가능) sfn: gif 애니메이션의 특정 프레임을 출력합니다.

fltr[ ]: 선명하게 하기, 흐리게 하기, 회전, 워터마크, 테두리, 마스킹, 색상 조정 등 다양한 효과를 가질 수 있는 필터입니다.

사용 데모:

//加载类库文件

 require_once &#39;path/to/ThumbLib.inc.php&#39;;

 //实例化类库,传入你要处理的图片的地址可以是网络地址,也可以是本地地址

 $thumb = PhpThumbFactory::create(&#39;http://www.shlongyingjixie.com/&#39;);

 //把图片等比缩小到最大宽度 100px或者最高100px,当只输入一个参数的时候,是限制最宽的尺寸。

 $thumb->resize(100, 100);

 //把图片等比缩小到原来的百分数,比如50就是原来的50%。

 $thumb->resizePercent(50);

 //截取一个175px * 175px的图片,注意这个是截取,超出的部分直接裁切掉,不是强制改变尺寸。
 $thumb->adaptiveResize(175, 175);

 //从图片的中心计算,截取200px * 100px的图片。

 $thumb->cropFromCenter(200, 100);

 //截图,前两个参数分别是需要解出的图片的右上角的坐标X,Y。 后面两个参数是需要解出的图片宽,高。

 $thumb->crop(100, 100, 300, 200);
 
 //把图片顺时针反转180度

 $thumb->rotateImageNDegrees(180);

 //保存(生成)图片,你可以保存其他格式,详细参考文档

 $thumb->save( &#39;NewPath/Of/image.jpg &#39; );

요약: 위 내용은 이 글의 전체 내용입니다. 모든 분들의 공부에 도움이 되었으면 좋겠습니다.

관련 권장사항:

php 양식 파일 iframe 비동기 업로드 예시 분석

PHP에서 구현한 Redis 다중 라이브러리 선택 기능 싱글턴 클래스(자세한 ​​설명)

PHP 사용자 정의 함수를 사용하여 Get 여부를 확인합니다. /포스트 /Ajax 제출방법 상세설명

위 내용은 썸네일 이미지를 생성하는 PHP 클래스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.