【问题标题】:How to auto resize an image for an image preview on the client side?如何在客户端自动调整图像大小以进行图像预览?
【发布时间】:2011-09-11 04:53:31
【问题描述】:

当用户注册到我的网站时,我正在使用此脚本为用户显示图像预览。我把它设置在客户端。换句话说,图片不是为预览而上传的。

尝试自动调整用户选择的图像的大小,以在重新显示在页面上时保持其纵横比。最大尺寸 150x150。

<script type='text/javascript'>
function userImage(file) {
    if(document.all)
        document.getElementById('showImage').src = file.value;
    else
        document.getElementById('showImage').src = file.files.item(0).getAsDataURL();
    if(document.getElementById('showImage').src.length > 0)
        document.getElementById('showImage').style.display = 'block';
}
</script>

<input type='file' name='avatar' onchange='userImage(this);' />
<img id='showImage' style='display:none;' />

【问题讨论】:

    标签: javascript image autoresize


    【解决方案1】:

    将建议更改为更简单的模型。请注意,IE 可能需要您的网站位于受信任区域才能显示图片

    <script type='text/javascript'>
    function userImage(file) {
        var img = document.getElementById("img1");
        img.onload=function() { this.parentNode.style.display="" }
        img.src=(file.files)?file.files.item(0).getAsDataURL():file.value;
    }
    </script>
    
    <input type="file" name="avatar" onchange="userImage(this);" />
    <div id="showImage" style="display:none" ><img name="img1" id="img1" src="dummy.gif" width="150" /></div>
    

    【讨论】:

      【解决方案2】:

      如果你是/可以使用 JQuery。检查此以获得通过预期高度并计算比例宽度的比例宽度。

       function GetWidth(expectedHeight )
                      {
                         var width = $("#showImage").width();
                         var height = $("#showImage").height();
                         var targetWidth = Math.round(expectedHeight * width / height);
                             $("#showImage").attr("width", targetWidth );
                             $("#showImage").attr("width", expectedHeight );
      
                      }
      
      
      
       with javascript 
      
           function GetWidth(expectedHeight )
           {                      
           var img = document.createElement("img");
           var width = img.width;
           var height = img.height;
           var targetWidth = Math.round(expectedHeight * width / height);
           img.width=targetWidth ;
           img.height =  expectedHeight ;
          }
      

      【讨论】:

        猜你喜欢
        • 2013-12-30
        • 1970-01-01
        • 2013-02-15
        • 2018-09-20
        • 1970-01-01
        • 1970-01-01
        • 2012-04-27
        • 1970-01-01
        • 2011-01-06
        相关资源
        最近更新 更多