本文實例講述了JS實現按比例縮放圖片的方法。分享給大家供大家參考,具體如下:
js版本:
function resizeImage(obj, MaxW, MaxH) { var imageObject = obj; var state = imageObject.readyState; if(state!='complete') { setTimeout("resizeImage("+imageObject+","+MaxW+","+MaxH+")",50); return; } var oldImage = new Image(); oldImage.src = imageObject.src; var dW = oldImage.width; var dH = 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; } }
使用很簡單:<img src="../pic.jpg" onload='resizeImage(this,60,90)> 就OK了;
注:等比例放縮的時候會出現抖動的情況,處理方法很簡單,你在img的屬性先設置它的widht和height,這樣的話加載的時候絕對不會超過這個尺寸,等你js運行好之後就會調到你所規定的比例,絕對不會以下撐到很大。
同時也附上C#版本的
/// <summary> /// 按比例縮放圖片 /// </summary> /// <param name="imgUrl">圖片的路徑</param> /// <param name="imgHeight">圖片的高度</param> /// <param name="imgWidth">圖片的寬度</param> /// <returns></returns> public static string GetImageSize(string imgUrl,int imgHeight,int imgWidth) { string fileName = System.Web.HttpContext.Current.Server.MapPath(imgUrl); string strResult = string.Empty; if(System.IO.File.Exists(fileName) && imgHeight != 0 && imgWidth != 0) { decimal desWidth;decimal desHeight;//目標寬高 System.Drawing.Image objImage = System.Drawing.Image.FromFile(fileName); decimal radioAct = (decimal)objImage.Width/(decimal)objImage.Height;//原始圖片的寬高比 decimal radioLoc = (decimal)imgWidth/(decimal)imgHeight;//圖片位的寬高比 if(radioAct > radioLoc)//原始圖片比圖片位寬 { decimal dcmZoom = (decimal)imgWidth/(decimal)objImage.Width; desHeight = objImage.Height*dcmZoom; desWidth = imgWidth; } else { decimal dcmZoom = (decimal)imgHeight/(decimal)objImage.Height; desWidth = objImage.Width*dcmZoom; desHeight = imgHeight; } objImage.Dispose(); //釋放資源 strResult = "width=\"" + Convert.ToString((int)desWidth) + "\" height=\"" + Convert.ToString((int)desHeight) + "\" "; } return strResult; }
希望本文所述對大家JavaScript程序設計有所幫助。