The front end modifies the size of the input uploaded image

Posted by Cless on Fri, 06 Dec 2019 17:18:54 +0100

My intention is to compress the quality of the picture, and accidentally write it to modify the width and height of the picture;

1. HTML code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>

</head>

<body>
    <div>
        <input type="file" name="" id="upload_img">
        <img src="" alt="" id="upload_img_preview">
    </div>
</body>
<script>
   
</script>
<script src="js/a.js"></script>
</html>

2. Code of js:

It uses img.onload, fileReader interface to read files, canvas drawing technology,

First, add a listening event to the input,

var ipt =document.getElementById('upload_img');
ipt.addEventListener('change',function(e){

    var file=e.target.files[0];
  
})

Use filereader function to read pictures when input ting and uploading pictures

Call readAsDataURL in the chang e function of input;

reader.readAsDataURL(file);

First declare a reader=new FileReader();

When the reader.readAsDataURL(file) is completed, the onload interface will be called:

When the file is read successfully, an event to call img.onload is returned;

Before calling, declare an img =new Image(); and canvas=document.createElement('create');context=canvas.getContext('2d');

In img.onload, judge the size of this image and the size of the required image, then draw it on canvas, and finally export canvas as base64 image and present it on the page;

img.onload = function () {
    var imgWidth=this.width//Width of uploaded image
    imgHeight = this.width,//Height of uploaded image
    maxWidth=1024,//Maximum picture width
        maxHeight = 1024,//Picture maximum height
    targetWidth=imgWidth,//Width of last picture
    targetHeight=imgHeight//Height of last picture
    // If the width or height of the picture is greater than the maximum width and height of the picture
    if(imgWidth>maxWidth||imgHeight>maxHeight){
        // Width greater than height
        if(imgWidth/imgHeight>maxWidth/maxHeight){
            targetWidth=maxWidth;
            targetHeight=Math.round(maxWidth*(imgWidth/imgHeight))
        }
        // Less than high
        else{
            targetHeight=maxHeight;
            targetWidth=Math.round(maxHeight*(imgHeight/imgWidth));
        }
    }
    canvas.width=targetWidth;//canvas width = image width
    canvas.height=targetHeight;//canvas height = image height
    context.clearRect(0,0,targetWidth,targetHeight)//Clean up canvas
    context.drawImage(img,0,0,targetWidth,targetHeight)//canvas drawing
    var newUrl=canvas.toDataURL('image',0.92);//canvas export to base64
    upload_img_preview.src=newUrl
}

 

Topics: Front-end IE less