【Convert base64 code to image and preview】

  1. Introduction to development tools and requirements
    (1) Development tools: HBuilder
    (2) Database: SQLite
    (3) Component library: uni-app
    (4) Requirements: (Backend) Encrypt image information, and the frontend receives a base64 code. The front end needs to use this information to convert it into <image src="imageURL"></image>the imageURL in order to display the picture. For the information returned by the backend, what we need is "picture type" and "picture information"
    insert image description here
    insert image description here

  2. Display the base64 code as a picture
    (1) format: the front-end should display the base64-encoded picture, which has a certain format, that is, data:图片类型;base64,base64码的图片信息
    (2) stitch the data returned by the back-end into the format we want and display it

<template>
	<view>
 	   <!--image是uni-app的组件-->
 	   <!--src需动态获取并,从这里可自定义方法,拼接成我们需要的格式然后返回,这样就可以展示了-->
	   <!--click点击事件用来预览base64图片的->
 	   <image :src="previewPhoto(picture.图片类型, picture.图片信息chunk)" @click="handlePreview(picture.图片类型,picture.图片信息chunk)"></image>
	</view>
</template>

<script>
	export default {
    
    
		data(){
    
    },
		methods:{
    
    
		    // 将base64码转换,并显示出图片
			previewPhoto(type, chunk){
    
    
				let imgURL = "data" + ":" + type + ";" + "base64," + chunk;
				return imgURL;
			}
		}
    }
</script>

  1. Preview base64 image

uni-app 自带组件image在触发点击事件时,不支持通过previewImage预览图片。因此需要利用插件

Principle: Convert base64 to a normal image before previewing, and the converted image will be automatically saved in the cache, and the address of the preview image is the cache address of the converted image, so that you can preview it

(1) Download the plug-in address: https://ext.dcloud.net.cn/plugin?id=123
(2) Use HBuilderX to import the plug-in
insert image description here
(3) Import it where it is needed, and the default path is under src

<template>
	<view>
	   <!--click点击事件用来预览base64图片的->
 	   <image :src="" @click="handlePreview(picture.图片类型,picture.图片信息chunk)"></image>
	</view>
</template>

<script>
import {
    
    base64ToPath} from '@/js_sdk/mmmm-image-tools/index.js'
export default {
    
    
	data(){
    
    },
	methods:{
    
    
	    // 预览图片
		handlePreview(type, chunk) {
    
    
			uni.showLoading({
    
    
				title: '预览加载中'
			})
			// imgURL为所要预览的base64图片
			let imgURL = 'data' + ":" + type+ ";" + "base64," + chunk;
			let imagesArry = [];
			base64ToPath(imgURL).then(path => {
    
    
				uni.hideLoading();
				imagesArry[0] = path
				uni.previewImage({
    
    
					current: 0,
					urls: imagesArry
				})
			})
		},
	}
}
</script>

Guess you like

Origin blog.csdn.net/weixin_47375144/article/details/129593728