User Tools

Site Tools


Differences

This shows you the differences between two versions of the page.

Link to this comparison view

js:tips:resize-image [2019-10-21 09:43] (current)
ziggi created
Line 1: Line 1:
 +=====JS image resize=====
 +
 +<code html>
 +<input id="​imageFile"​ type="​file">​
 +<input type="​button"​ value="​Resize Image" onclick="​ResizeImage()"​ />
 +<img src=""​ id="​output">​
 +</​code>​
 +
 +<code js>
 +function ResizeImage() {
 +    var filesToUpload = document.getElementById('​imageFile'​).files;​
 +    var file = filesToUpload[0];​
 +
 +    var img = document.createElement("​img"​);​
 +    var reader = new FileReader();​
 +    reader.onload = function(e) {
 +        img.src = e.target.result
 +    }
 +    reader.readAsDataURL(file);​
 +
 +    var ctx = canvas.getContext("​2d"​);​
 +    ctx.drawImage(img,​ 0, 0);
 +
 +    var MAX_WIDTH = 800;
 +    var MAX_HEIGHT = 600;
 +    var width = img.width;
 +    var height = img.height;
 +
 +    if (width > height) {
 +        if (width > MAX_WIDTH) {
 +            height *= MAX_WIDTH / width;
 +            width = MAX_WIDTH;
 +        }
 +    } else {
 +        if (height > MAX_HEIGHT) {
 +            width *= MAX_HEIGHT / height;
 +            height = MAX_HEIGHT;
 +        }
 +    }
 +    ctx.width = width;
 +    ctx.height = height;
 +    var ctx = canvas.getContext("​2d"​);​
 +    ctx.drawImage(img,​ 0, 0, width, height);
 +
 +    var dataurl = canvas.toDataURL("​image/​png"​);​
 +    document.getElementById('​output'​).src = dataurl;
 +}
 +</​code>​