Wechat applet selects pictures and converts them to base64

Generally, images are uploaded to the backend in the form of base64, which takes up less memory and reduces the number of server visits during use. The official API provided by WeChat does not support uploading multiple files, so if you are uploading images, it is a good idea to use base64 encoded strings.

Related APIs

wx.chooseImage(Object object)

Function description

Select a picture from your local photo album or take a photo with your camera.


wx.getImageInfo(Object object)

Function description

Get image information. Network images need to be configured with a download domain name before they can take effect.

Insert image description here


FileSystemManager.readFile(Object object)

Function description

Read local file content. The maximum size of a single file is 100M.

Insert image description here


The WeChat applet selects pictures and converts them to base64. The code is as follows:

// 选择图片并自动转成base64编码(count:文件可选数,imgType:转base64时图片类型)
	chooseImageToBase64(count) {
    
    
		return new Promise((resolve, reject) => {
    
    
			wx.chooseImage({
    
    
				count,
				sizeType: 'compressed',
				success: (res) => {
    
    
					console.log(res)
					var tempFilePaths = res.tempFilePaths
					var base64ImgArr = [];
					tempFilePaths.forEach((item) => {
    
    
						wx.getImageInfo({
    
    
							src: item,
							success(imageInfo) {
    
    
								var imgType = imageInfo.type
								wx.getFileSystemManager().readFile({
    
    
									filePath: item, //选择图片返回的相对路径
									encoding: "base64", //这个是很重要的
									success: res => {
    
     //成功的回调
										//返回base64格式
										var base64Str = 'data:image/' + imgType + ';base64,' + res.data
										base64ImgArr.push(base64Str)
										if (base64ImgArr.length == tempFilePaths.length) {
    
    
											resolve(base64ImgArr)
										}
									},
									fail: err => {
    
    
										console.log(err)
										reject(err)
									}
								})
							}
						})
					})
				},
				fail: (err) => {
    
    
					console.log(err)
				}
			})
		})
	},

The format is a bit doll, you can optimize it yourself!

this.chooseImageToBase64(1).then(res=>{
    
    
	console.log(res)//图片base64 (数组)
	//.....
})

uni-app can also be used by changing wx to uni

Guess you like

Origin blog.csdn.net/weixin_44646763/article/details/122526672