vue实现将图像文件转换为base64
程序员文章站
2022-06-09 22:34:25
目录将图像文件转换为base641、image转base642、base64图像直接显示在标签vue网络图片转base64单张图片转base64多张图片转base64将图像文件转换为base64直入主...
将图像文件转换为base64
直入主题,上代码(其实用的还是filereader)
1、image转base64
imagetobase64 (file) { var reader = new filereader() reader.readasdataurl(file) reader.onload = () => { console.log('file 转 base64结果:' + reader.result) this.iconbase64 = reader.result } reader.onerror = function (error) { console.log('error: ', error) } }
2、base64图像直接显示在标签
<el-form-item prop="iconbase64"> <img :src="iconbase64" v-show="isshow" /> </el-form-item>
vue网络图片转base64
单张图片转base64
<script> methods: { //异步执行 imageurltobase64() { //一定要设置为let,不然图片不显示 let image = new image(); //解决跨域问题 image.setattribute('crossorigin', 'anonymous'); let imageurl = "http://img1.imgtn.bdimg.com/it/u=4012470373,3540768040&fm=26&gp=0.jpg"; image.src = imageurl let that = this; //image.onload为异步加载 image.onload = () => { var canvas = document.createelement("canvas"); canvas.width = image.width; canvas.height = image.height; var context = canvas.getcontext('2d'); context.drawimage(image, 0, 0, image.width, image.height); var quality = 0.8; //这里的dataurl就是base64类型 var dataurl = canvas.todataurl("image/jpeg", quality);//使用todataurl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长! } }, } </script>
多张图片转base64
<script> data() { return { base64datas: [], } methods: { imageurltobase64(){ let data = [ "http://bigf.cqugeo.cn/landslip/res/defaultimages/default.png", "http://bigf.cqugeo.cn/landslip/res/defaultimages/default.png", "http://bigf.cqugeo.cn/landslip/res/defaultimages/default.png" ] this.imageurltobase64(data, 1, data.length); }, //采用递归同步执行 onloadimg(data, i, len) { //一定要设置为let,不然图片不显示 let image = new image(); //解决跨域问题 image.setattribute('crossorigin', 'anonymous'); let imageurl = "http://bigf.cqugeo.cn/landslip/res/defaultimages/default.png"; image.src = imageurl let that = this; //image.onload为异步加载 image.onload = () => { var canvas = document.createelement("canvas"); canvas.width = image.width; canvas.height = image.height; var context = canvas.getcontext('2d'); context.drawimage(image, 0, 0, image.width, image.height); var quality = 0.8; //这里的dataurl就是base64类型 var dataurl = canvas.todataurl("image/jpeg", quality);//使用todataurl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长! //数组存放图片base64 that.base64datas.push(dataurl); //递归执行图片url转base64 i = i + 1; if (i <= len) { that.onloadimg(data1, i, len) } } }, } </script>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。