PHP圖像處理繪圖、水印、驗(yàn)證碼、圖像壓縮技術(shù)實(shí)例總結(jié)(3)

2019-01-22 15:21:02 來源:互聯(lián)網(wǎng)作者:佚名 人氣: 次閱讀 649 條評論

文章主要介紹了PHP圖像處理技術(shù),結(jié)合實(shí)例形式總結(jié)分析了php繪圖、水印、驗(yàn)證碼、圖像壓縮等相關(guān)函數(shù)、功能與圖形繪制實(shí)現(xiàn)技巧,需要的朋友可以參考下:1、繪圖  場景:...

4、圖像壓縮

  對圖像進(jìn)行壓

  縮處理非常簡單,因?yàn)榫鸵粋€函數(shù)

  參數(shù)1:目標(biāo)圖像資源(畫布)

  參數(shù)2:等待壓縮圖像資源

  參數(shù)3:目標(biāo)點(diǎn)的x坐標(biāo)

  參數(shù)4:目標(biāo)點(diǎn)的y坐標(biāo)

  參數(shù)5:原圖的x坐標(biāo)

  參數(shù)6:原圖的y坐標(biāo)

  參數(shù)7:目的地寬度(畫布寬)

  參數(shù)8:目的地高度(畫布高)

  參數(shù)9:原圖寬度

  參數(shù)10:原圖高度

  imagecopyresampled($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)

  封裝的圖像壓縮類

  1. <?php
  2. /*
  3. * 圖像壓縮處理類
  4. */
  5. class Thumb
  6. {
  7. private $_filename; //等待壓縮的圖像
  8. private $_thumb_path = 'thumb/'; //壓縮圖像的保存目錄
  9. public function __set($p,$v)
  10. {
  11. if(property_exists($this,$p)){
  12. $this -> $p = $v;
  13. }
  14. }
  15. //構(gòu)造方法初始化需要壓縮的圖像
  16. public function __construct($file)
  17. {
  18. if(!file_exists($file)){
  19. echo '文件有誤,不能壓縮';
  20. return;
  21. }
  22. $this -> _filename = $file;
  23. }
  24. //圖像壓縮處理
  25. function makeThumb($area_w,$area_h)
  26. {
  27. $src_image = imagecreatefrompng($this->_filename);
  28. $res = getimagesize($this->_filename);
  29. echo '<pre>';
  30. var_dump($res);
  31. die;
  32. $dst_x = 0;
  33. $dst_y = 0;
  34. $src_x = 0;
  35. $src_y = 0;
  36. //原圖的寬度、高度
  37. $src_w = imagesx($src_image); //獲得圖像資源的寬度
  38. $src_h = imagesy($src_image); //獲得圖像資源的高度
  39. if($src_w / $area_w < $src_h/$area_h){
  40. $scale = $src_h/$area_h;
  41. }
  42. if($src_w / $area_w >= $src_h/$area_h){
  43. $scale = $src_w / $area_w;
  44. }
  45. $dst_w = (int)($src_w / $scale);
  46. $dst_h = (int)($src_h / $scale);
  47. $dst_image = imagecreatetruecolor($dst_w,$dst_h);
  48. $color = imagecolorallocate($dst_image,255,255,255);
  49. //將白色設(shè)置為透明色
  50. imagecolortransparent($dst_image,$color);
  51. imagefill($dst_image,0,0,$color);
  52. imagecopyresampled($dst_image,$src_image,$dst_x,$dst_y,$src_x,$src_y,$dst_w,$dst_h,$src_w,$src_h);
  53. //可以在瀏覽器直接顯示
  54. //header("Content-Type:image/png");
  55. //imagepng($dst_image);
  56. //分目錄保存壓縮的圖像
  57. $sub_path = date('Ymd').'/';
  58. //規(guī)范:上傳的圖像保存到upload目錄,壓縮的圖像保存到thumb目錄
  59. if(!is_dir($this -> _thumb_path . $sub_path)){
  60. mkdir($this -> _thumb_path . $sub_path,0777,true);
  61. }
  62. $filename = $this -> _thumb_path . $sub_path.'thumb_'.$this->_filename;
  63. //也可以另存為一個新的圖像
  64. imagepng($dst_image,$filename);
  65. return $filename;
  66. }
  67. }
  68. $thumb = new Thumb('upload.jpg');
  69. $thumb -> _thumb_path = 'static/thumb/';
  70. $file = $thumb -> makeThumb(100,50);
  71. // var_dump($file);

  以上就是PHP圖像處理繪圖、水印、驗(yàn)證碼、圖像壓縮技術(shù)實(shí)例總結(jié)介紹,希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。