图片动态缩放PHP与JS算法
07-20
这个算法写好多次了,虽然简单,但每次都得想一次,这里做个备份。
因为GD函数进行缩放,必须有宽和高,而在浏览器中,会自动按照比率调整宽高,所以两个函数稍有区别。
- #PHP版
- # $s_width 原图宽
- # $s_height 原图高
- # $t_width 目标文件最大宽
- # $t_height 目标文件最大高
- function ReSizePic( $s_width , $s_height , $t_width , $t_height)
- {
- if( $s_width / $s_height > $t_width / $t_height && $s_width > $t_width)
- {
- $t_height = $s_height * $t_width / $s_width;
- $t_width = $t_width;
- }
- else if( $s_width / $s_height > $t_width / $t_height && $s_width < = $t_width)
- {
- $t_height = $s_height;
- $t_width = $s_width;
- }
- else if( $s_width / $s_height < $t_width / $t_height && $s_height > $t_height)
- {
- $t_width = $s_width*$t_height/$s_height;
- $t_height = $t_height;
- }
- else if( $s_width / $s_height < $t_width / $t_height && $s_height <= $t_height)
- {
- $t_height = $s_height;
- $t_width = $s_width;
- }
- return array( "width" => $t_width , "height" => $t_height );
- }
- #JS版
- # obj 图片对象
- # maxWidth 显示最大宽
- # maxHeight 显示最大高
- function ReSizePic( obj , maxWidth , maxHeight )
- {
- if( ( obj.width/obj.height >= maxWidth/maxHeight ) && obj.width > maxWidth )
- {
- obj.width = maxWidth;
- }
- else if( ( obj.width/obj.height < maxWidth/maxHeight ) && obj.height > maxHeight )
- {
- obj.height = maxHeight;
- }
- }