この記事の例では、JS で画像を比例的に拡大縮小する方法について説明します。参考のために皆さんと共有してください。詳細は次のとおりです:
js バージョン:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
使い方はとても簡単です:
/// <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;
}