A-A+
javascript实现图片等比例缩放代码
1、预先定义好图片显示的标准宽度和高度。
2、如果图片的大小超过了标准定义,那么等比例压缩图片。
3、如果图片的大小等于标准定义,那么按照标准宽度和高度显示图片。
4、如果图片的大小小于标准定义,那么不对图片进行任何压缩处理。代码如下:
- //设置图片自动调整
- function SetImgSize(pimg,iw,ih) { //pimg对象,iw缩略图宽度,ih缩略图高度
- var img = new Image();
- img.src = pimg.src;
- var w = iw;
- var h = ih;
- if(img.width>0 && img.height>0)
- {
- if(img.width>iw||img.height>ih)
- {
- if((iw / ih) > (img.width / img.height))
- {
- h = ih;
- w = img.width * (ih / img.height);
- }
- else
- {
- w = iw;
- h = img.height * (iw / img.width);
- }
- }
- else
- {
- w = img.width;
- h = img.height;
- }
- }
- pimg.width=w;
- pimg.height=h;
- pimg.style.display="";
- }
调用相当简单,代码如下:
- <img width="150" height="110" src="<?php echo $pic;?>" onload="SetImgSize(this,150,110)" />
直接调用便可.
css代码如下:
- .thumbimg { max-width: 530px; max-height: 530px; }/* for firefox & ie7 */
- * html .thumbimg {width: expression(this.width > 530 && this.width > this.height ? "530px" :auto); height:expression(this.height >530 ? "530px":auto);}/* for ie6
方法二,代码如下:
- img {
- width:expression(this.offsetwidth>160 ? 160 : true); /*自行修改图片宽度*/
- height:expression(this.offsetheight>180 ? 180 : true); /*自行修改图片高度*/
- }
js整个页面都自动等比例缩放,代码如下:
- <script language="javascript" type="text/javascript">
- function DrawImage()
- {
- var FitWidth = 200,FitHeight = 200;
- var ImgD = document.getElementById('Image1');
- var image = new Image();
- image.src=ImgD.src;
- if(image.width>0 && image.height>0)
- {
- if(image.width/image.height>= FitWidth/FitHeight)
- {
- if(image.width>FitWidth)
- {
- ImgD.width=FitWidth;
- ImgD.height=(image.height*FitWidth)/image.width;
- }
- else
- {
- ImgD.width=image.width;
- ImgD.height=image.height;
- }
- }
- else
- {
- if(image.height>FitHeight)
- {
- ImgD.height=FitHeight;
- ImgD.width=(image.width*FitHeight)/image.height;
- }
- else
- {
- ImgD.width=image.width;
- ImgD.height=image.height;
- }
- }
- }
- }
- DrawImage();
- </script>