jemiloii
jemiloii

Reputation: 25719

How to auto resize an image for an image preview on the client side?

I am using this script to display an image preview for users when they register to my site. I have it set to be on the client side. Other-words, the image isn't uploaded for the preview.

Trying to auto resize the image the user selects to maintain it's apect ratio when it is display back on the page. Max size 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;' />

Upvotes: 0

Views: 2284

Answers (2)

mplungjan
mplungjan

Reputation: 177701

Changed the suggestion to a simpler model. Please note that IE may need your site to be in trusted zone to allow it to show the image

<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>

Upvotes: 1

Pit Digger
Pit Digger

Reputation: 9780

If you are/can use JQuery. Check this for Getting Proportional width where you pass expected height and calculate proportional width.

 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 ;
    }

Upvotes: 0

Related Questions