在处理网页图片缩略图时,很难保证图片统一大小,直接设置图片大小又会导致图片拉伸,造成图片模糊,本文介绍的代码可以在图片加载完成后自动按比例调整图片大小。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageAutoZoom.aspx.cs" Inherits="UI_ImageAutoZoom" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js 实现网页图片按比例缩放-by wangtao</title>
<script type="text/javascript" src="../Misc/Js/Core/Jquery.js"></script>
</head>
<body>
<script type="text/javascript">
function ImageAutoZoom(Img,FitWidth,FitHeight)
{
var image=new Image();
image.src=Img.src;
if(image.width>0 && image.height>0)
{
if(image.width/image.height>= FitWidth/FitHeight)
{
if(image.width>FitWidth)
{
Img.width=FitWidth;
Img.height=(image.height*FitWidth)/image.width;
}
else if(image.hight>FitHeight)
{
Img.height=FitHeight;
Img.width=(image.width*FitHeight)/image.height;
}
else
{
Img.width=FitWidth;
Img.height=FitHeight;
}
}
}
}
</script>
<form id="ImageAutoZoomform" runat="server">
<div>
<img src="../Misc/Image/Test/war3.jpg" height="200" width="200" alt="按比例缩放图片" onload="ImageAutoZoom(this,200,200)" />
</div>
</form>
</body>
</html>