前端 base64下载图片(亲测可用)
前端base64转图片 下载(亲测可用)
·
二进制流转base64传送门https://blog.csdn.net/m0_60067716/article/details/124606097
二进制流转base64这里就不介绍啦,可以看我上面的文章。
base64转图片核心代码
- imgSrc:就是base64地址哈
saveImg() {
var base64 = this.imgSrc.toString(); // imgSrc 就是base64哈
var byteCharacters = atob(
base64.replace(/^data:image\/(png|jpeg|jpg);base64,/, "")
);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: undefined,
});
var aLink = document.createElement("a");
aLink.download = "图片名称.jpg"; //这里写保存时的图片名称
aLink.href = URL.createObjectURL(blob);
aLink.click();
},
完整代码
<template>
<div class="app">
<img :src="imgSrc" alt="图片" />
<button @click="saveImg">点击保存图片</button>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "app",
data() {
return {
imgSrc: "",
};
},
methods: {
// 二进制流转换为base64 格式。
getBase64(data) {
const blob = new Blob([data], { type: "image/jpg" }); //类型一定要写!!!
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
},
// base64 保存图片
saveImg() {
var base64 = this.imgSrc.toString(); // imgSrc 就是base64哈
var byteCharacters = atob(
base64.replace(/^data:image\/(png|jpeg|jpg);base64,/, "")
);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: undefined,
});
var aLink = document.createElement("a");
aLink.download = "图片名称.jpg"; //这里写保存时的图片名称
aLink.href = URL.createObjectURL(blob);
aLink.click();
},
},
mounted() {
//网上随便找的图片
const url =
"https://img0.baidu.com/it/u=73689209,3130028231&fm=253&fmt=auto&app=138&f=JPEG";
axios
.get(url, {
responseType: "blob", //一定要传!!!
})
.then((res) => {
console.log(res.data, "二进制流");
this.getBase64(res.data).then((binary) => {
console.log(binary, "base64");
this.imgSrc = binary;
});
});
},
};
</script>
更多推荐
已为社区贡献3条内容
所有评论(0)