image.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /*
  3. * Image handle class
  4. * by lijg 20181031
  5. */
  6. class ImageLib{
  7. public function __construct(){
  8. //TODO
  9. }
  10. public function setImageType($imgPath='', $type=''){
  11. if(empty($imgPath) || empty($type)){
  12. return false;
  13. }
  14. $im = null;
  15. switch($type){
  16. case 1:
  17. $im = imagecreatefromgif($imgPath);
  18. break;
  19. case 2:
  20. $im = imagecreatefromjpeg($imgPath);
  21. break;
  22. case 3:
  23. $im = imagecreatefrompng($imgPath);
  24. break;
  25. default:
  26. return false;
  27. }
  28. return $im;
  29. }
  30. public function exportImage($imgPath='', $dim, $suf='thumb'){
  31. if(empty($imgPath) || empty($dim)){
  32. return false;
  33. }
  34. $imgInfo = getimagesize($imgPath);
  35. $path = pathinfo($imgPath);
  36. $imgName = "{$path['dirname']}/{$suf}/{$path['filename']}_{$suf}.{$path['extension']}";
  37. switch($imgInfo[2]){
  38. case 1:
  39. imagegif($dim, $imgName);
  40. break;
  41. case 2:
  42. imagejpeg($dim, $imgName);
  43. break;
  44. case 3:
  45. imagepng($dim, $imgName);
  46. break;
  47. default:
  48. return false;
  49. }
  50. return $imgName;
  51. }
  52. public function scaleImage($imgPath='', $setWidth='100', $setHeight='100', $suf ='thumb'){
  53. if(empty($imgPath)){
  54. return false;
  55. }
  56. $imgInfo = getimagesize($imgPath);
  57. $width = $imgInfo[0];
  58. $height = $imgInfo[1];
  59. $rate = ($setWidth/$width)>($setHeight/$height)?$setHeight/$height:$setWidth/$width;
  60. $newWidth = floor($width*$rate);
  61. $newHeight = floor($height*$rate);
  62. $sim = $this->setImageType($imgPath, $imgInfo[2]);
  63. $dim = imagecreatetruecolor($newWidth, $newHeight);
  64. imagecopyresampled($dim, $sim, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  65. $image = $this->exportImage($imgPath, $dim, $suf);
  66. imagedestroy($sim);
  67. imagedestroy($dim);
  68. return $image;
  69. }
  70. public function __destruct(){
  71. //TODO
  72. }
  73. }