处理页面载入图片js(等比例压缩图片)

第一页面html  <div class="admin">${answer.content}</div>

 <div class="adminss">${answer.content}</div>

第二循环压缩${answer.content}内容中的大图片

<script>

jQuery(function(){

    setTimeout('imgLoad()'1000)//延长载入一分钟

});

function 'imgLoad(){//页面载入时循环遍历压缩admin以下内容带有img标志的图片

     jQuery('.admin img').each(function(i){

     DrawImage(jQuery('.admin img').eq(i),600,600);

});

     jQuery('.adminss img').each(function(i){

     DrawImage(jQuery('.adminss img').eq(i),500,500);

});)//页面载入时循环遍历压缩admin以下内容带有img标志的图片 500,500用户自己定义

}

</script>

第三 压缩图片的js

<script language="JavaScript">

<!--

//图片按比例缩放

var flag=false;
function DrawImage(ImgD,iwidth,iheight){
    //參数(图片,同意的宽度,同意的高度) 

    var image=ImD;

    image.src=ImgD.attr('src');
    if(image.width()>0 && image.height()>0){
    flag=true;
    if(image.width()/image.height()>= iwidth/iheight){
        if(image.width()>iwidth){  
        ImgD.width(iwidth);
        ImgD.height((image.height()*iwidth)/image.width());
        }else{
        ImgD.width(image.width());  
        ImgD.height(image.height());
        }
        ImgD.alt=image.width+"×"+image.height;
        }
else{
        if(image.height()>iheight){  
        ImgD.height(iheight);
        ImgD.width((image.width()*iheight)/image.height());        
        }else{
        ImgD.width(image.width());  
        ImgD.height(image.height());
        }
        ImgD.alt=image.width+"×"+image.height;
        }
    }

//-->

</script>


另外一种需求例如以下:

在Web上显示图片,通常都会有图片显示比例问题,假设不给<img />限制width和height,那么假设图片大了就会将整个页面挤乱,图片小了又会使图片失真。
    我的需求例如以下:
        1、预先定义好图片显示的标准宽度和高度。
        2、假设图片的大小超过了标准定义,那么等比例压缩图片。
        3、假设图片的大小等于标准定义。那么依照标准宽度和高度显示图片。
        4、假设图片的大小小于标准定义,那么不正确图片进行不论什么压缩处理。
    可能是我搜索的keyword不正确吧。在网上找了非常长时间。才找到,感觉非常好使。代码例如以下

<script language="JavaScript">

<!--

//图片按比例缩放

var flag=false;
function DrawImage(ImgD,iwidth,iheight){
    //參数(图片,同意的宽度,同意的高度)
    var image=new Image();
    image.src=ImgD.src;
    if(image.width>0 && image.height>0){
    flag=true;
    if(image.width/image.height>= iwidth/iheight){
        if(image.width>iwidth){  
        ImgD.width=iwidth;
        ImgD.height=(image.height*iwidth)/image.width;
        }else{
        ImgD.width=image.width;  
        ImgD.height=image.height;
        }
        ImgD.alt=image.width+"×"+image.height;
        }
else{
        if(image.height>iheight){  
        ImgD.height=iheight;
        ImgD.width=(image.width*iheight)/image.height;        
        }else{
        ImgD.width=image.width;  
        ImgD.height=image.height;
        }
        ImgD.alt=image.width+"×"+image.height;
        }
    }

//-->

</script>

调用:<img src="images/toplogo.gif" onload="javascript:DrawImage(this,100,100)">
posted @ 2017-05-21 10:58  llguanli  阅读(186)  评论(0编辑  收藏  举报