uniapp converts the image into base64 format and displays it with url

Renderings:

 coding:

<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>

annotation:

_this.base64Image = "data:image/jpeg;base64," + data.data means what?

this.base64Imageis a data binding for displaying images in the view. By this.base64Imageassigning a string starting with "data:image/jpeg;base64," and then splicing the Base64-encoded image data behind, the image data in Base64 format can be displayed on the page as a URL

uni.chooseImage?

Choose an image from your local photo album or take a photo with your camera

Documentation: uni.chooseImage(OBJECT) | uni-app official website

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

Use the readFile method of FileSystemManager in uni-app to read files

Documentation: uni.getFileSystemManager() | uni-app official website

filePath(Required): The path of the file to be read, which can be a relative path or an absolute path.

encoding(Optional): The encoding format of the file, the default value is 'utf8'. If you need to convert the file content to Base64 format, you need to set the value to 'base64'.

success(Optional): The callback function after the file is read successfully, receiving a parameter indicating the read file data.

fail(Optional): The callback function when the file reading fails, receiving a parameter indicating the error message.

Guess you like

Origin blog.csdn.net/weixin_52479803/article/details/131457370