uniapp base64转为blob请帮我写一个完整的页面示范
<p>以下是一个完整的uniapp页面示范,用于将base64转为blob:</p>
<template>
<div>
<input type="file" @change="handleFileChange" accept="image/*" />
<img :src="imageUrl" />
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: null,
};
},
methods: {
handleFileChange(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const base64 = reader.result.split(",")[1];
const blob = this.base64ToBlob(base64);
const objectUrl = URL.createObjectURL(blob);
this.imageUrl = objectUrl;
};
},
base64ToBlob(base64) {
const byteString = atob(base64);
const mimeString = "image/jpeg";
// 将byteString转为ArrayBuffer
const arrayBuffer = new ArrayBuffer(byteString.length);
const uint8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
uint8Array[i] = byteString.charCodeAt(i);
}
// 生成blob
const blob = new Blob([arrayBuffer], { type: mimeString });
return blob;
},
},
};
</script>
<style scoped>
img {
max-width: 100%;
height: auto;
}
</style>
<p>在这个示例中,我们首先提供了一个input元素,用于选择要转换的图片文件。当用户选择一个文件时,我们使用FileReader API读取该文件,并将其转换为base64格式的字符串。然后,我们使用自定义方法base64ToBlob将base64字符串转换为Blob。最后,我们使用URL.createObjectURL将Blob转换为图像文件的URL,并将其设置为img元素的src属性</p>
原文地址: https://www.cveoy.top/t/topic/hdU6 著作权归作者所有。请勿转载和采集!