zoukankan      html  css  js  c++  java
  • 图片上传时用Canvas 压缩和加水印

    用菜鸟教程模拟的

    菜鸟对应链接 https://www.runoob.com/try/try-cdnjs.php?filename=tryhtml5_canvas_tut_img

    <!DOCTYPE html>
    <html>
    <head> 
    <meta charset="utf-8"> 
    <title>菜鸟教程(runoob.com)</title> 
    </head>
    <body>
    
    <p>Image to use:</p>
    <img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277"><p>Canvas:</p>
    <canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
    您的浏览器不支持 HTML5 canvas 标签。</canvas>
    <img id="screamaa" src="" alt="The Scream" width="220" height="277">
          <input type="file"
                  id="uploadFile"
                  accept="image/*"
                />
    <script>
    
    var imgff= function (base64){
          var bili = 0.7; //压缩后的图片尺寸,0.7就是70%
         
    var img=new Image() 
    img.src = base64
        console.log("img.width", img.width,"height", img.height)
    img.onload = function() {
        var c=document.getElementById("myCanvas");
        var ctx=c.getContext("2d");
          //图片地址加载完后执行操作
            var newWidth = img.width; //压缩后图片的宽度
            var newHeight = img.height; //压缩后图片的高度
            c.width = newWidth; //压缩图的宽度
            c.height = newHeight; //压缩图的高度
            ctx.drawImage(img, 0, 0, newWidth,newHeight); //压缩 把图片放到画布上
        
        ctx.font="30px Arial";
        ctx.fillStyle = "#ffffff"; //设置水印
        ctx.fillText("你好", 40, 40); //选择水印位置
        
        
        let newBase64 = c.toDataURL("image/jpeg", 0.7);
        console.log("dnewBase64",newBase64)
        var c=document.getElementById("screamaa");
        c.src =newBase64
    } 
    }
    
     var eleUploadFile = document.getElementById('uploadFile');
        
       eleUploadFile.addEventListener('change', function(event) {
            var file = event.target.files[0] || event.target.dataTransfer.files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var base64 = e.target.result;
                // canvas压缩图片,并且回调显示
                imgff(base64)
            }
            reader.readAsDataURL(file);
        });
    
    </script>
    
    </body>
    </html>
  • 相关阅读:
    webpack基础
    LeetCode232. 用栈实现队列做题笔记
    mysql 时间加减一个月
    leetcode 1381. 设计一个支持增量操作的栈 思路与算法
    LeetCode 141. 环形链表 做题笔记
    leetcode 707. 设计链表 做题笔记
    leetcode 876. 链表的中间结点 做题笔记
    leetcode 143. 重排链表 做题笔记
    leetcode 1365. 有多少小于当前数字的数字 做题笔记
    LeetCode1360. 日期之间隔几天 做题笔记
  • 原文地址:https://www.cnblogs.com/qhantime/p/14185120.html
Copyright © 2011-2022 走看看