php按比例生成缩略图代码

  1. <?php
  2. class My_Lib_simpleimage {
  3. var $image;
  4. var $image_type;
  5. function load($filename) {
  6. //$filename 文件的临时文件名 $_FILES['name']['tmp_name']
  7. $image_info = getimagesize($filename);
  8. $this->image_type = $image_info[2];
  9. if( $this->image_type == IMAGETYPE_JPEG ) {
  10. $this->image = imagecreatefromjpeg($filename);
  11. } elseif( $this->image_type == IMAGETYPE_GIF ) {
  12. $this->image = imagecreatefromgif($filename);
  13. } elseif( $this->image_type == IMAGETYPE_PNG ) {
  14. $this->image = imagecreatefrompng($filename);
  15. }
  16. }
  17. function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
  18. if( $image_type == IMAGETYPE_JPEG ) {
  19. imagejpeg($this->image,$filename,$compression);
  20. } elseif( $image_type == IMAGETYPE_GIF ) {
  21. imagegif($this->image,$filename);
  22. } elseif( $image_type == IMAGETYPE_PNG ) {
  23. imagepng($this->image,$filename);
  24. }
  25. if( $permissions != null) {
  26. chmod($filename,$permissions);
  27. }
  28. }
  29. function output($image_type=IMAGETYPE_JPEG) {
  30. if( $image_type == IMAGETYPE_JPEG ) {
  31. imagejpeg($this->image);
  32. } elseif( $image_type == IMAGETYPE_GIF ) {
  33. imagegif($this->image);
  34. } elseif( $image_type == IMAGETYPE_PNG ) {
  35. imagepng($this->image);
  36. }
  37. } //开源代码phpfensi.com
  38. function getWidth() {
  39. return imagesx($this->image);
  40. }
  41. function getHeight() {
  42. return imagesy($this->image);
  43. }
  44. #设置缩略图片高度
  45. function resizeToHeight($height) {
  46. $ratio = $height / $this->getHeight();
  47. $width = $this->getWidth() * $ratio;
  48. $this->resize($width,$height);
  49. }
  50. #设置缩略图片宽度
  51. function resizeToWidth($width) {
  52. $ratio = $width / $this->getWidth();
  53. $height = $this->getheight() * $ratio;
  54. $this->resize($width,$height);
  55. }
  56. function scale($scale) {
  57. $width = $this->getWidth() * $scale/100;
  58. $height = $this->getheight() * $scale/100;
  59. $this->resize($width,$height);
  60. }
  61. function resize($width,$height) {
  62. $new_image = imagecreatetruecolor($width, $height);
  63. imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
  64. $this->image = $new_image;
  65. }
  66. }
  67. ?>