uniapp将图片转化为base64格式,并用url展示出来

效果图:

 编码:

<template>
	<view class="container">
		<button @click="chooseImage">选择图片</button>
		<image v-if="base64Image" :src="base64Image"></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				base64Image: ''
			};
		},
		methods: {
			chooseImage() {
				let _this = this
				uni.chooseImage({
					count: 1,
					success(res) {
						const tempFilePath = res.tempFilePaths[0];
						uni.getFileSystemManager().readFile({
							filePath: tempFilePath,
							encoding: "base64",
							success(data) {
								console.log("图片的Base64数据:", data.data);
								_this.base64Image = "data:image/jpeg;base64," + data.data;
							},
							fail(error) {
								console.log("读取文件失败:", error);
							}
						});
					},
					fail(error) {
						console.log("选择图片失败:", error);
					}
				});
			}
		}
	}
</script>

<style>
	.container {
		margin: 20px;
	}
</style>

注解:

_this.base64Image = "data:image/jpeg;base64," + data.data表示什么?

this.base64Image是一个用于在视图中展示图片的数据绑定。通过给this.base64Image赋值一个以"data:image/jpeg;base64,"开头的字符串,然后将Base64编码的图片数据拼接在后面,就可以将这个Base64格式的图片数据作为URL来展示在页面上

uni.chooseImage?

从本地相册选择图片或使用相机拍照

文档:uni.chooseImage(OBJECT) | uni-app官网

uni.getFileSystemManager().readFile({})?

使用uni-app中FileSystemManager的readFile方法读取文件

文档:uni.getFileSystemManager() | uni-app官网

filePath(必填):要读取的文件路径,可以是相对路径或绝对路径。

encoding(可选):文件的编码格式,默认值为 'utf8'。如果需要将文件内容转换为 Base64 格式,则需要将该值设置为 'base64'。

success(可选):文件读取成功后的回调函数,接收一个参数表示读取到的文件数据。

fail(可选):文件读取失败时的回调函数,接收一个参数表示错误信息。

猜你喜欢

转载自blog.csdn.net/weixin_52479803/article/details/131457370