JS实现按比例缩放图片的方法(附C#版代码)
本文实例讲述了JS实现按比例缩放图片的方法。分享给大家供大家参考,具体如下:
js版本:
functionresizeImage(obj,MaxW,MaxH)
{
varimageObject=obj;
varstate=imageObject.readyState;
if(state!='complete')
{
setTimeout("resizeImage("+imageObject+","+MaxW+","+MaxH+")",50);
return;
}
varoldImage=newImage();
oldImage.src=imageObject.src;
vardW=oldImage.width;
vardH=oldImage.height;
if(dW>MaxW||dH>MaxH)
{
a=dW/MaxW;b=dH/MaxH;
if(b>a)a=b;
dW=dW/a;dH=dH/a;
}
if(dW>0&&dH>0)
{
imageObject.width=dW;
imageObject.height=dH;
}
}
使用很简单:<imgsrc="../pic.jpg"onload='resizeImage(this,60,90)>就OK了;
注:等比例放缩的时候会出现抖动的情况,处理方法很简单,你在img的属性先设置它的widht和height,这样的话加载的时候绝对不会超过这个尺寸,等你js运行好之后就会调到你所规定的比例,绝对不会以下撑到很大。
同时也附上C#版本的
///<summary>
///按比例缩放图片
///</summary>
///<paramname="imgUrl">图片的路径</param>
///<paramname="imgHeight">图片的高度</param>
///<paramname="imgWidth">图片的宽度</param>
///<returns></returns>
publicstaticstringGetImageSize(stringimgUrl,intimgHeight,intimgWidth)
{
stringfileName=System.Web.HttpContext.Current.Server.MapPath(imgUrl);
stringstrResult=string.Empty;
if(System.IO.File.Exists(fileName)&&imgHeight!=0&&imgWidth!=0)
{
decimaldesWidth;decimaldesHeight;//目标宽高
System.Drawing.ImageobjImage=System.Drawing.Image.FromFile(fileName);
decimalradioAct=(decimal)objImage.Width/(decimal)objImage.Height;//原始图片的宽高比
decimalradioLoc=(decimal)imgWidth/(decimal)imgHeight;//图片位的宽高比
if(radioAct>radioLoc)//原始图片比图片位宽
{
decimaldcmZoom=(decimal)imgWidth/(decimal)objImage.Width;
desHeight=objImage.Height*dcmZoom;
desWidth=imgWidth;
}
else
{
decimaldcmZoom=(decimal)imgHeight/(decimal)objImage.Height;
desWidth=objImage.Width*dcmZoom;
desHeight=imgHeight;
}
objImage.Dispose();//释放资源
strResult="width=\""+Convert.ToString((int)desWidth)+"\"height=\""
+Convert.ToString((int)desHeight)+"\"";
}
returnstrResult;
}
希望本文所述对大家JavaScript程序设计有所帮助。