ImageZip.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace app\common\services;
  3. class ImageZip {
  4. /**
  5. * 压缩/缩略
  6. * @param $srcFile
  7. * @param $number
  8. * @param $type
  9. * @return bool
  10. */
  11. public static function makeThumb($srcFile, $number, $type)
  12. {
  13. //type 1 压缩 2 缩略
  14. $img = getimagesize($srcFile);
  15. if (!is_file($srcFile) || $img == false) {
  16. return false;
  17. }
  18. list($src_width, $src_height, $src_type) = $img; //原图宽度、高度
  19. $memory_limit = trim(ini_get('memory_limit'), 'M');
  20. $img_memory = $src_width * $src_height * 3 * 1.7;
  21. if ($img_memory > $memory_limit * 1024 * 1024) { //imagecreatetruecolor方法生成图片资源时会占用大量的服务器内存,所以在上传大图、长图时不能使用
  22. return false;
  23. }
  24. if ($type == 2) {
  25. if ($src_width < $number) {
  26. $width = $src_width;
  27. $number = $src_width;
  28. } else {
  29. $width = $number;
  30. }
  31. $height = $src_height * $number / $src_width;
  32. } else {
  33. $width = $src_width;
  34. $height = $src_height;
  35. }
  36. switch ($src_type) {
  37. case 1 :
  38. $image_type = 'gif';
  39. break;
  40. case 2 :
  41. $image_type = 'jpeg';
  42. break;
  43. case 3 :
  44. $image_type = 'png';
  45. break;
  46. case 15 :
  47. $image_type = 'wbmp';
  48. break;
  49. default :
  50. return false;
  51. }
  52. $image_canvas = imagecreatetruecolor($width, $height); //创建画布
  53. $bg = imagecolorallocatealpha($image_canvas, 255, 255, 255, 127);
  54. imagefill($image_canvas, 0, 0, $bg);
  55. $imagecreatefromfunc = 'imagecreatefrom'.$image_type;
  56. $image_resources = $imagecreatefromfunc($srcFile);
  57. imagecopyresampled($image_canvas, $image_resources, 0, 0, 0, 0, $width, $height, $src_width, $src_height); //缩放图片(高精度)
  58. if ($type == 2) {
  59. $imagefunc = 'image'.$image_type;
  60. $imagefunc($image_canvas, $srcFile);
  61. } else {
  62. imagejpeg($image_canvas, $srcFile, $number);
  63. }
  64. imagedestroy($image_canvas);
  65. imagedestroy($image_resources);
  66. return true;
  67. }
  68. }