一、问题:
base64数据图片在开发工具中显示正常,真机模拟不显示;
二、解决
将base64数据图片转存到本地临时文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
namespace Image { /** * 获取图片全路径 * @param name 图片名 * @returns */ export const getImageUrl = (name: string): string => import.meta.env.VITE_IMG + name /** * 获取图片信息 * @param src 图片路径 * @returns */ export const getImageInfo = (src: string): Promise<string> => new Promise((resolve, reject) => { uni.getImageInfo({ src, success: res => resolve(res.path), fail: err => reject(err) }) }) /** * 将 base64 图片数据转本地图片 * @param base64Data base64图片数据 * @returns */ export const getBase64ImageInfo = (base64Data: string): Promise<string> => { const fs = uni.getFileSystemManager() return new Promise((resolve, reject) => { const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64Data) || [] if (!format) { reject(new Error('ERROR_BASE64SRC_PARSE')) } const FILE_BASE_NAME = 'tmp_base64src' const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}` const buffer = uni.base64ToArrayBuffer(bodyData) fs.writeFile({ filePath, data: buffer, encoding: 'binary', success: () => resolve(filePath), fail: () => reject(new Error('ERROR_BASE64SRC_WRITE')) }) }) } /** * 删除本地临时文件 * @param filePath 临时图片地址 * @returns */ export const removeTmpImage = (filePath: string): Promise<void> => new Promise(() => { const fs = uni.getFileSystemManager() fs.unlink({ filePath, success: res => console.log(res), fail: e => console.log(e) }) }) } export default Image |