图片太大且规格不统一,显示的控制需要靠JavaScript来完成,用在移动设备上时显示效果不好且流量巨大,需要对现有图片库的图片进行一次处理,生成符合移动设备用的缩略图,将原来客户端JS做的工作转移到服务器端用PHP的GD库来集中处理。
图片源与需要的大小:
1 | $src_img = "wallpaper.jpg" ; |
剪裁图像,保证图像区域最大化显示,并按比例缩放到指定大小
一开始采用了 imagecopyresized 方法进行图像等比缩小,实际操作后发现,图像缩小后燥点非常严重。后再换用 imagecopysampled 方法,该方法会对图像进行重新采样,对缩小的图像进行平滑处理,使清晰度得到很大提高。
02 | list( $src_w , $src_h )= getimagesize ( $src_img ); |
04 | $dst_scale = $dst_h / $dst_w ; |
05 | $src_scale = $src_h / $src_w ; |
07 | if ( $src_scale >= $dst_scale ){ |
09 | $h = intval ( $dst_scale * $w ); |
15 | $w = intval ( $h / $dst_scale ); |
22 | $source =imagecreatefromjpeg( $src_img ); |
23 | $croped =imagecreatetruecolor( $w , $h ); |
24 | imagecopy( $croped , $source , 0, 0, $x , $y , $src_w , $src_h ); |
28 | $target = imagecreatetruecolor( $dst_w , $dst_h ); |
29 | $final_w = intval ( $w * $scale ); |
30 | $final_h = intval ( $h * $scale ); |
31 | imagecopyresampled( $target , $croped , 0, 0, 0, 0, $final_w , $final_h , $w , $h ); |
35 | imagejpeg( $target , "$timestamp.jpg" ); |
36 | imagedestroy( $target ); |
无损裁剪图片
上传图片的时候, 经常是不确定比例, 显示的时候又得统一, 这个方案可以解决
03 | $imgstream = file_get_contents ( $image ); |
04 | $im = imagecreatefromstring( $imgstream ); |
20 | $sy = abs (( $x - $y )/2.5); |
25 | if (function_exists( "imagecreatetruecolor" )) { |
26 | $dim = imagecreatetruecolor( $yy , $xx ); |
28 | $dim = imagecreate( $yy , $xx ); |
30 | imageCopyreSampled ( $dim , $im ,0,0, $sx , $sy , $yy , $xx , $thumbw , $thumbh ); |
31 | header ( "Content-type: image/jpeg" ); |
32 | imagejpeg ( $dim , false, 100); |