我的本意是压缩图片的质量,一不小心写成了修改图片的宽高;

1、HTML部分代码:

<!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、js部分代码:

在这里面用到了图片加载(img.onload),fileReader接口读取文件,canvas画图技术,

首先,给input添加监听事件,

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

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

在input上传图片的时候用filereader函数读取图片

前端修改input上传的图片大小

 在input的chang函数里面调用readAsDataURL;

reader.readAsDataURL(file);

要先全局声明一个reader=new FileReader();

在reader.readAsDataURL(file);调用完成的时候会调用onload接口:

前端修改input上传的图片大小

 当文件读取成功,返回一个去调用img.onload事件;

调用之前先全局声明一个img =new Image();和canvas=document.createElement('create');context=canvas.getContext('2d');

在img.onload里面判断这个图片的大小和所需图片的大小,然后绘制到canvas上面,最后将canvas导出成为base64图片呈现到页面上面;

img.onload = function () {
    var imgWidth=this.width//上传图片的宽
    imgHeight = this.width,//上传图片的高
    maxWidth=1024,//图片最大宽
        maxHeight = 1024,//图片最大高
    targetWidth=imgWidth,//最后图片的宽
    targetHeight=imgHeight//最后图片的高
    // 如果图片的宽或者高大于图片的最大宽高
    if(imgWidth>maxWidth||imgHeight>maxHeight){
        // 宽大于高
        if(imgWidth/imgHeight>maxWidth/maxHeight){
            targetWidth=maxWidth;
            targetHeight=Math.round(maxWidth*(imgWidth/imgHeight))
        }
        // 款小于高
        else{
            targetHeight=maxHeight;
            targetWidth=Math.round(maxHeight*(imgHeight/imgWidth));
        }
    }
    canvas.width=targetWidth;//canvas的宽=图片的宽
    canvas.height=targetHeight;//canvas的高=图片的高
    context.clearRect(0,0,targetWidth,targetHeight)//清理canvas
    context.drawImage(img,0,0,targetWidth,targetHeight)//canvas绘图
    var newUrl=canvas.toDataURL('image',0.92);//canvas导出成为base64
    upload_img_preview.src=newUrl
}

 

相关文章:

  • 2022-12-23
  • 2021-07-02
  • 2021-08-01
  • 2022-12-23
  • 2021-10-04
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
猜你喜欢
  • 2022-12-23
  • 2021-09-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
  • 2021-12-06
相关资源
相似解决方案