PHP生成缩略图

 1 private function create_scaled_image($file_path){
 2         $file_name = basename($file_path);
 3         $new_file_path = dirname($file_path) . DIRECTORY_SEPARATOR . $this->thumbnail['upload_dir'] . DIRECTORY_SEPARATOR;
 4         if(!file_exists($new_file_path))
 5             @mkdir($new_file_path);
 6         $new_file_path .= $file_name;
 7         list($img_width, $img_height) = @getimagesize($file_path);
 8         if(!$img_width || !$img_height){
 9             return false;
10         }
11         $scale = min(
12                 $this->thumbnail['max_width'] / $img_width, $this->thumbnail['max_height'] / $img_height
13         );
14         if($scale >= 1){
15             if($file_path !== $new_file_path){
16                 return copy($file_path, $new_file_path);
17             }
18             return true;
19         }
20         $new_width = $img_width * $scale;
21         $new_height = $img_height * $scale;
22         $new_img = @imagecreatetruecolor($new_width, $new_height);
23         switch(strtolower(substr(strrchr($file_name, '.'), 1))){
24             case 'jpg':
25             case 'jpeg':
26                 $src_img = @imagecreatefromjpeg($file_path);
27                 $write_image = 'imagejpeg';
28                 $image_quality = isset($this->thumbnail['jpeg_quality']) ?
29                         $this->thumbnail['jpeg_quality'] : 75;
30                 break;
31             case 'gif':
32                 @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0));
33                 $src_img = @imagecreatefromgif($file_path);
34                 $write_image = 'imagegif';
35                 $image_quality = null;
36                 break;
37             case 'png':
38                 @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0));
39                 @imagealphablending($new_img, false);
40                 @imagesavealpha($new_img, true);
41                 $src_img = @imagecreatefrompng($file_path);
42                 $write_image = 'imagepng';
43                 $image_quality = isset($this->thumbnail['png_quality']) ?
44                         $this->thumbnail['png_quality'] : 9;
45                 break;
46             default:
47                 $src_img = null;
48         }
49         $success = $src_img && @imagecopyresampled(
50                         $new_img, $src_img, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height
51                 ) && $write_image($new_img, $new_file_path, $image_quality);
52         // Free up memory (imagedestroy does not delete files):
53         @imagedestroy($src_img);
54         @imagedestroy($new_img);
55         return $success;
56     }
posted @ 2012-06-05 13:01  无嗔  阅读(194)  评论(0编辑  收藏  举报