这篇文章给大家分享的是有关vue如何实现将图像文件转换为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 = [
"https://cache.tdyun.com/upload/information/20220209/112/953450.png",
"https://cache.tdyun.com/upload/information/20220209/112/953450.png",
"https://cache.tdyun.com/upload/information/20220209/112/953450.png"
]
this.imageUrlToBase64(data, 1, data.length);
},
//采用递归同步执行
onloadImg(data, i, len) {
//一定要设置为let,不然图片不显示
let image = new Image();
//解决跨域问题
image.setAttribute('crossOrigin', 'anonymous');
let imageUrl = "https://cache.tdyun.com/upload/information/20220209/112/953450.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>
感谢各位的阅读!关于“vue如何实现将图像文件转换为base64”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!