自定义裁剪图片大小

 1 <?php
 2 /**
 3 * 图像裁剪
 4 * @param $title string 原图路径
 5 * @param $content string 需要裁剪的宽
 6 * @param $encode string 需要裁剪的高
 7 */
 8 function imagecropper($source_path, $target_width, $target_height)
 9 {
10 $source_info = getimagesize($source_path);
11 $source_width = $source_info[0];
12 $source_height = $source_info[1];
13 $source_mime = $source_info['mime'];
14 $source_ratio = $source_height / $source_width;
15 $target_ratio = $target_height / $target_width;
16 
17 // 源图过高
18 if ($source_ratio > $target_ratio)
19 {
20 $cropped_width = $source_width;
21 $cropped_height = $source_width * $target_ratio;
22 $source_x = 0;
23 $source_y = ($source_height - $cropped_height) / 2;
24 }
25 // 源图过宽
26 elseif ($source_ratio < $target_ratio)
27 {
28 $cropped_width = $source_height / $target_ratio;
29 $cropped_height = $source_height;
30 $source_x = ($source_width - $cropped_width) / 2;
31 $source_y = 0;
32 }
33 // 源图适中
34 else
35 {
36 $cropped_width = $source_width;
37 $cropped_height = $source_height;
38 $source_x = 0;
39 $source_y = 0;
40 }
41 
42 switch ($source_mime)
43 {
44 case 'image/gif':
45 $source_image = imagecreatefromgif($source_path);
46 break;
47 
48 case 'image/jpeg':
49 $source_image = imagecreatefromjpeg($source_path);
50 break;
51 
52 case 'image/png':
53 $source_image = imagecreatefrompng($source_path);
54 break;
55 
56 default:
57 return false;
58 break;
59 }
60 
61 $target_image = imagecreatetruecolor($target_width, $target_height);
62 $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
63 
64 // 裁剪
65 imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
66 // 缩放
67 imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
68 
69 //保存图片到本地(两者选一)
70 //$randNumber = mt_rand(00000, 99999). mt_rand(000, 999);
71 //$fileName = substr(md5($randNumber), 8, 16) .".png";
72 //imagepng($target_image,'./'.$fileName);
73 //imagedestroy($target_image);
74 
75 //直接在浏览器输出图片(两者选一)
76 header('Content-Type: image/jpeg');
77 imagepng($target_image);
78 imagedestroy($target_image);
79 imagejpeg($target_image);
80 imagedestroy($source_image);
81 imagedestroy($target_image);
82 imagedestroy($cropped_image);
83 }
84 
85 //调用
86 //imagecropper('./img033.jpg',300,300);
87 imagecropper('./img033.jpg',140,140);
88 //imagecropper('./img033.jpg',55,55);
89 ?>

 

posted @ 2017-12-29 16:02  个人小站  阅读(838)  评论(0)    收藏  举报