(PHP 4 >= 4.0.6, PHP 5)
imagecopyresampled — 重采样拷贝部分图像并调整大小
imagecopyresampled() 将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,减小了图像的大小而仍然保持了极大的清晰度。如果源和目标的宽度和高度不同,则会进 行相应的图像收缩和拉伸。坐标指的是左上角。本函数可用来在同一幅图内部拷贝(如果 dst_image
和src_image
相同的话)区域,但如果区域交迭的话则结果不可预知。
函数参数如下:
bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h ) |
今天根据这个函数写了个方法,能够等比缩放图片的大小,并且可以设置宽度固定高度等比缩放,或者高度固定宽度等比缩放,或者设置最大宽和最大高。具体代码如下:
/** * 图片缩放函数(可设置高度固定,宽度固定或者最大宽高,支持gif/jpg/png三种类型) * Author : Specs * Homepage: http://9iphp.com * * @param string $source_path 源图片 * @param int $target_width 目标宽度 * @param int $target_height 目标高度 * @param string $fixed_orig 锁定宽高(可选参数 width、height或者空值) * @return string */ function myImageResize($source_path, $target_width = 200, $target_height = 200, $fixed_orig = ''){ $source_info = getimagesize($source_path); $source_width = $source_info[0]; $source_height = $source_info[1]; $source_mime = $source_info['mime']; $ratio_orig = $source_width / $source_height; if ($fixed_orig == 'width'){ //宽度固定 $target_height = $target_width / $ratio_orig; }elseif ($fixed_orig == 'height'){ //高度固定 $target_width = $target_height * $ratio_orig; }else{ //最大宽或最大高 if ($target_width / $target_height > $ratio_orig){ $target_width = $target_height * $ratio_orig; }else{ $target_height = $target_width / $ratio_orig; } } switch ($source_mime){ case 'image/gif': $source_image = imagecreatefromgif($source_path); break; case 'image/jpeg': $source_image = imagecreatefromjpeg($source_path); break; case 'image/png': $source_image = imagecreatefrompng($source_path); break; default: return false; break; } $target_image = imagecreatetruecolor($target_width, $target_height); imagecopyresampled($target_image, $source_image, 0, 0, 0, 0, $target_width, $target_height, $source_width, $source_height); //header('Content-type: image/jpeg'); $imgArr = explode('.', $source_path); $target_path = $imgArr[0] . '_new.' . $imgArr[1]; imagejpeg($target_image, $target_path, 100); } |
用法如下:
myImageResize($filename, 200, 200); //最大宽高 myImageResize($filename, 200, 200, 'width'); //宽度固定 myImageResize($filename, 200, 200, 'height'); //高度固定