PHP按一定比例压缩图片的方法

图片压缩是我们日常开发中经常使用的操作,在如今需求很多的情况往往,上传的一张图片会被压缩成不同比例的图片,每次去操作也是一件非常繁琐的事情,于是进行了封装了一个压缩图片的操作类,希望大家遇到后,不用再为写很多压缩图片代码烦恼了。

压缩图片的工具类:

  1. <?php
  2. /**
  3. 图片压缩操作类
  4. v1.0
  5. */
  6. class Image{
  7. private $src;
  8. private $imageinfo;
  9. private $image;
  10. public $percent = 0.1;
  11. public function __construct($src){
  12. $this->src = $src;
  13. }
  14. /**
  15. 打开图片
  16. */
  17. public function openImage(){
  18. list($width, $height, $type, $attr) = getimagesize($this->src);
  19. $this->imageinfo = array(
  20. 'width'=>$width,
  21. 'height'=>$height,
  22. 'type'=>image_type_to_extension($type,false),
  23. 'attr'=>$attr
  24. );
  25. $fun = "imagecreatefrom".$this->imageinfo['type'];
  26. $this->image = $fun($this->src);
  27. }
  28. /**
  29. 操作图片
  30. */
  31. public function thumpImage(){
  32. $new_width = $this->imageinfo['width'] * $this->percent;
  33. $new_height = $this->imageinfo['height'] * $this->percent;
  34. $image_thump = imagecreatetruecolor($new_width,$new_height);
  35. //将原图复制带图片载体上面,并且按照一定比例压缩,极大的保持了清晰度
  36. imagecopyresampled($image_thump,$this->image,0,0,0,0,$new_width,$new_height,$this->imageinfo['width'],$this->imageinfo['height']);
  37. imagedestroy($this->image);
  38. $this->image = $image_thump;
  39. }
  40. /**
  41. 输出图片
  42. */
  43. public function showImage(){
  44. header('Content-Type: image/'.$this->imageinfo['type']);
  45. $funcs = "image".$this->imageinfo['type'];
  46. $funcs($this->image);
  47. }
  48. /**
  49. 保存图片到硬盘
  50. */
  51. public function saveImage($name){
  52. $funcs = "image".$this->imageinfo['type'];
  53. $funcs($this->image,$name.'.'.$this->imageinfo['type']);
  54. }
  55. /**
  56. 销毁图片
  57. */
  58. public function __destruct(){
  59. imagedestroy($this->image);
  60. }
  61. }
  62. ?>

测试:

  1. <?php
  2. require 'image.class.php';
  3. $src = "001.jpg";
  4. $image = new Image($src);
  5. $image->percent = 0.2;
  6. $image->openImage();
  7. $image->thumpImage();
  8. $image->showImage();
  9. $image->saveImage(md5("aa123"));
  10. ?>