003 | * 说明:函数功能是把一个图像裁剪为任意大小的图像,图像不变形 |
004 | * 参数说明:输入需要处理图片的文件名,生成新图片的保存文件名,生成新图片的宽,生成新图片的高 |
006 | // 获得任意大小图像,不足地方拉伸,不产生变形,不留下空白 |
007 | function my_image_resize( $src_file , $dst_file , $new_width , $new_height ) |
009 | if ( $new_width < 1|| $new_height < 1){ |
010 | echo 'params widthorheighterror!' ; |
013 | if (! file_exists ( $src_file )) { |
014 | echo $src_file . ' isnotexists!' ; |
018 | $type = exif_imagetype( $src_file ); |
019 | $support_type = array (IMAGETYPE_JPEG, IMAGETYPE_PNG,IMAGETYPE_GIF); |
020 | if (!in_array( $type , $support_type , true)){ |
021 | echo 'this typeofimagedoesnotsupport!onlysupportjpg,giforpng' ; |
027 | $src_img = imagecreatefromjpeg( $src_file ); |
030 | $src_img = imagecreatefrompng( $src_file ); |
033 | $src_img = imagecreatefromgif( $src_file ); |
036 | echo 'Load imageerror!' ; |
041 | $ratio_w = (1.0* $new_width ) / $w ; |
042 | $ratio_h = (1.0* $new_height ) / $h ; |
044 | // 生成的图像的高宽比原来的都小,或都大,原则是取大比例放大,取大比例缩小(缩小的比例就比较小了) |
045 | if ( $ratio_w < 1&& $ratio_h < 1|| $ratio_w > 1&& $ratio_h > 1){ |
046 | if ( $ratio_w < $ratio_h ) { |
051 | // 定义一个中间的临时图像,该图像的宽高比正好满足目标要求 |
052 | $inter_w = (int)( $new_width / $ratio ); |
053 | $inter_h = (int)( $new_height / $ratio ); |
054 | $inter_img = imagecreatetruecolor( $inter_w , $inter_h ); |
055 | imagecopy( $inter_img , $src_img , 0,0,0,0, $inter_w , $inter_h ); |
056 | // 生成一个以最大边长度为大小的是目标图像$ratio比例的临时图像 |
058 | $new_img = imagecreatetruecolor( $new_width , $new_height ); |
059 | imagecopyresampled( $new_img , $inter_img , 0,0,0,0, $new_width , $new_height , $inter_w , $inter_h ); |
062 | imagejpeg( $new_img , $dst_file , 100); |
066 | imagepng( $new_img , $dst_file , 100); |
069 | imagegif( $new_img , $dst_file , 100); |
075 | $ratio = $ratio_h > $ratio_w ? $ratio_h : $ratio_w ; |
077 | // 定义一个中间的大图像,该图像的高或宽和目标图像相等,然后对原图放大 |
078 | $inter_w = (int)( $w * $ratio ); |
079 | $inter_h = (int)( $h * $ratio ); |
080 | $inter_img = imagecreatetruecolor( $inter_w , $inter_h ); |
082 | imagecopyresampled( $inter_img , $src_img , 0,0,0,0, $inter_w , $inter_h , $w , $h ); |
084 | $new_img = imagecreatetruecolor( $new_width , $new_height ); |
085 | imagecopy( $new_img , $inter_img , 0,0,0,0, $new_width , $new_height ); |
088 | imagejpeg( $new_img , $dst_file , 100); |
092 | imagepng( $new_img , $dst_file , 100); |
095 | imagegif( $new_img , $dst_file , 100); |
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理