一,js代码:
<template> <div> <img id="img" src="/static/image/dog.jpg" style="300px;" /><br/> <button @click="downImgByUrl">down by url</button> <button style="margin-left:10px;" @click="downImgByCanvas">down by canvas</button> </div> </template> <script> export default { name: "ImgDown", setup () { //得到图片的canvas,然后下载 const downImgByCanvas = () => { let id="img"; const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') //得到原始的宽高 let sourceImage = document.getElementById(id); canvas.width = sourceImage.naturalWidth; canvas.height = sourceImage.naturalHeight; //保存图片到canvas ctx.drawImage(sourceImage, 0, 0); downJpgByCanvas(canvas); } //得到图片的url,然后下载 const downImgByUrl = () => { let img = document.getElementById('img'); downJpgByUrl(img.src); } //下载图片:通过canvas const downJpgByCanvas = (canvas) => { var oA = document.createElement("a"); let time = timeFormat(); oA.download = "img_"+time+'.jpg';// 设置下载的文件名,默认是'下载' oA.href = canvas.toDataURL("image/jpeg"); document.body.appendChild(oA); oA.click(); oA.remove(); // 下载之后把创建的元素删除 } //下载图片:通过url const downJpgByUrl = (url) => { let time = timeFormat(); var a = document.createElement('a'); // 创建一个a节点插入的document var event = new MouseEvent('click') // 模拟鼠标click点击事件 a.download = "img_"+time+'.jpg'; // 设置a节点的download属性值 a.href = url; // 将图片的src赋值给a节点的href a.dispatchEvent(event) a.remove(); // 下载之后把创建的元素删除 } //补0 const add0 = (m) => { return m<10?'0'+m:m } //格式化时间 const timeFormat = ()=>{ var time = new Date(); var y = time.getFullYear(); var m = time.getMonth()+1; var d = time.getDate(); var h = time.getHours(); var mm = time.getMinutes(); var s = time.getSeconds(); let res = y+add0(m)+add0(d)+add0(h)+add0(mm)+add0(s); return res; } return { downImgByUrl, downImgByCanvas, } } } </script> <style scoped> </style>
说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果:
界面:
原图:
下载后大小:
最上面的文件,大小是359KB,是通过canvas下载的,
是因为canvas下载时重新生成了图片,所以文件体积发生了变化
三,查看vue框架的版本:
liuhongdi@lhdpc:/data/vue/pdf/image2pdf$ npm list vue image2pdf@0.1.0 /data/vue/pdf/image2pdf ├─┬ @vue/cli-plugin-babel@5.0.8 │ └─┬ @vue/babel-preset-app@5.0.8 │ ├─┬ @vue/babel-preset-jsx@1.3.0 │ │ └── vue@3.2.37 deduped invalid: "2.x" from node_modules/@vue/babel-preset-jsx │ └── vue@3.2.37 deduped └─┬ vue@3.2.37 └─┬ @vue/server-renderer@3.2.37 └── vue@3.2.37 deduped