通过JS,按照原比例控制图片尺寸

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Js压缩图片</title>
    <script type="text/javascript" >
        //img:图片对象
        //   w:宽度
        //   h:高度
        function ctlImg(img, w, h) {
            var img_Width = w;
            var img_Height = h;
            var w = img.width;
            var h = img.height;
            if (img.width > img_Width && img.height > img_Height) {
                if (w / img_Width > h / img_Height) {
                    img.width = img_Width;
                    img.height = parseInt(img_Width / w * h);
                }
                else {
                    img.height = img_Height;
                    img.width = parseInt(img_Height / h * w);
                }
                return true;
            }
            if (w > img_Width) {
                img.width = img_Width;
                img.height = parseInt(img_Width * (h / w));
            } else if (h > img_Height) {
                img.height = img_Height;
                img.width = parseInt(img_Height * (w / h));
            }
            return true;
        }
</script>
</head>
<body >
<img alt="" src="1.jpg "  onload="ctlImg(this,80,60)"/>
<img alt="" src="2.jpg "  onload="ctlImg(this,800000,600)"/>
<img alt="" src="3.jpg "  onload="ctlImg(this,80,60)"/>
<img alt="" src="4.jpg "  onload="ctlImg(this,8000,100)"/>

</body>
</html>

posted @ 2013-06-19 09:04  chengeng  阅读(497)  评论(0编辑  收藏  举报