Eduard Climov
Eduard Climov

Reputation: 193

How to resize image, but keep its proportions with javascript?

I have a "file" input and a function, called by event "onchange". What it does is resizing and showing image, but it's not exactly what I need.

<input type="file" id="imgUp" accept=".jpg" onchange="readURL(this);" > 

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
            $('#avatar,#image')
                .attr('src', e.target.result)
                .width(70)
                .height(70);
            };
            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

Is it possible to resize(keeping proportions) and show an image using Javascript, without jQuery?

Thank you in advance!

Upvotes: 1

Views: 1875

Answers (2)

Titus
Titus

Reputation: 22474

To preserver the aspect ration, you can set only the width or the height of the image instead of setting both of them.

Here is an example:

$('#avatar,#image').attr('src', e.target.result).width(70);

Or

$('#avatar,#image').attr('src', e.target.result).height(70);

And in vanilla Javascript:

var imgs = document.querySelectorAll("#image, #avatar");
for(var i = 0; i < imgs.length; i++){
     imgs[i].src = e.target.result;
     imgs[i].width = 70;// or imgs[i].height = 70;
}

DEMO

Upvotes: 2

Jamie Barker
Jamie Barker

Reputation: 8246

Change the implicit height and width declarations to max-height and max-width:

.css('max-width', '70px').css('max-height', '70px');

Using max height and max width sets the bounding box it should use, and then the image will fit within that at it's native aspect ratio.

Native vanilla JS:

.style.maxWidth = '70px';

.style.maxHeight = '70px';

If you're wanting to move away from jQuery to vanilla JS (I applaud you for doing so), try this helpful website.

Vanilla conversion for your code:

$('#avatar,#image')
  .attr('src', e.target.result)
  .width(70)
  .height(70);
};

becomes:

var elements = document.querySelectorAll('#avatar,#image');
Array.prototype.forEach.call(elements, function(el, i){
  el.setAttribute('src', e.target.result);
  el.style.maxWidth = '70px';
  el.style.maxHeight = '70px';
});

Upvotes: 4

Related Questions