
/**
 * 限制图片的宽度,如果宽度没有超过限制则不处理,如果超过则限制到指定的宽度,高度不限定
 * ImgD 图片对象
 * iwidth 最大宽度
 * 调用：<img src="071.jpg" onload="limitWidth(this,450)">
 */

function limitWidth(ImgD,iwidth){
    var image=new Image();
    image.src=ImgD.src;
    if(image.width>0 && image.width>iwidth){
		ImgD.width=iwidth;
    }
}

/**
 * 限制图片的高度,如果高度没有超过限制则让图片垂直居中,
 * 如果超过则限制到指定的高度,宽度不限定
 * ImgD 图片对象
 * iHeight 最大高度
 * divHeight 图片外围元素的高度,使用这个高度是为了处理垂直居中
 * 调用：<img src="071.jpg" onload="limitHeight(this,100,200)">
 */

function limitHeight(ImgD,iHeight,divHeight){
    var image=new Image();
    image.src=ImgD.src;
    if(image.height>0 && image.height>iHeight){
		ImgD.height=iHeight;
    }else{
		var mt = (divHeight-image.height)/2;	
		if(mt<=0) return;
		else ImgD.style.marginTop = mt+"px";	
    }
    
}

/**
 * 图片按比例缩放
 * ImgD 图片对象
 * iHeight 最大高度
 * iWidth 最大宽度
 * 调用：<img src="071.jpg" onload="resizeImage(this,100,100)">
 */

function resizeImg(ImgD,iWidth,iHeight){
	
	//参数(图片,允许的宽度,允许的高度)
    var image=new Image();
    image.src=ImgD.src;
    var width = image.width , height = image.height , dWidth = image.width , dHeight = image.height;
    if(image.width>0 && image.height>0){
	   
	    if(image.width/image.height>= iWidth/iHeight){
	        if(image.width>iWidth){  
	        	width=iWidth;
	        	height=(image.height*iWidth)/image.width;
	        }else{
	        	width=image.width;  
	        	height=image.height;
	        }
	    }else{
	        if(image.height>iHeight){  
	        	height=iHeight;
	        	width=(image.width*iHeight)/image.height;        
	        }else{
	        	width=image.width;  
	        	height=image.height;
	        }  
	    }
    }
    if(width != dWidth){
    	ImgD.width = width;
    }
    if(height != dHeight){	
    	ImgD.height = height;
    } 
}

