1 <?php
2 // 将图像等比放大或缩小
3 class resize{
4
5 private $src;
6 private $image;
7 private $width;
8 private $height;
9 private $imageType;
10 private $imageResize;
11 private $newWidth;
12 private $newHeight;
13
14 // 文件路径名,期待文件的宽度
15 public function __construct($fileName, $newWidth){
16
17 $this->src = $fileName;
18 $this->newWidth = $newWidth;
19 $this->imageType = exif_imagetype($fileName);
20 $this->image = $this->openImage($this->src);
21 if($this->image){
22 $this->width = imagesx($this->image);
23 $this->height = imagesy($this->image);
24 }
25
26
27 }
28
29
30 private function openImage($file){
31
32 switch ($this->imageType) {
33 case IMAGETYPE_GIF:
34 $img = imagecreatefromgif($file);
35 break;
36
37 case IMAGETYPE_JPEG:
38 $img = imagecreatefromjpeg($file);
39 break;
40
41 case IMAGETYPE_PNG:
42 $img = imagecreatefrompng($file);
43 break;
44 }
45
46 return $img;
47 }
48
49
50 private function saveImage(){
51
52 switch ($this->imageType) {
53 case IMAGETYPE_GIF:
54 header("Content-type: " . image_type_to_mime_type(IMAGETYPE_GIF));
55 imagegif($this->imageResize);
56 break;
57
58 case IMAGETYPE_JPEG:
59 header("Content-type: " . image_type_to_mime_type(IMAGETYPE_JPEG));
60 imagejpeg($this->imageResize);
61 break;
62
63 case IMAGETYPE_PNG:
64 header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
65 imagepng($this->imageResize);
66 break;
67 }
68
69 imagedestroy($this->image);
70 imagedestroy($this->imageResize);
71 }
72
73
74 public function resizeImage(){
75
76 $ratio = $this->height/$this->width;
77 $this->newHeight = $this->newWidth*$ratio;
78 $this->imageResize = imagecreatetruecolor($this->newWidth, $this->newHeight);
79 imagecopyresampled($this->imageResize, $this->image, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->width, $this->height);
80 $this->saveImage();
81 }
82
83 }
84
85
86 $img1 = new resize('GD/img/logo.png',50);
87 $img1->resizeImage();
88
89
90 ?>