一、将网络图片转换为base64格式
类似于:http://beta.erpstrong.com:9100/api/Inspiration/GetInspirationFile?filename=1680685765.jpgr
如上图片格式!!!
utlis/imgUrlToBase64.js
/**
* 将网络图片转换为base64格式
* @param {String} imgUrl 网络图片地址
* @returns {Promise} 返回Promise对象,resolve参数为base64格式的图片数据
*/
export function imgUrlToBase64(imgUrl) {
return new Promise((resolve, reject) => {
uni.request({
url: imgUrl,
responseType: "arraybuffer",
success: (res) => {
const base64 = uni.arrayBufferToBase64(res.data);
resolve("data:image/jpeg;base64," + base64);
},
fail: (err) => {
reject(err);
},
});
});
}
export default imgUrlToBase64
App.vue
<template>
<view class="content">
<button @click="starClick">点击</button>
</view>
</template>
<script>
import {
imgUrlToBase64
} from "@/utils/imgUrlToBase64.js";
export default {
data() {
return {
imgUrl: 'http://beta.erpstrong.com:9100/api/Inspiration/GetInspirationFile?filename=1680685765.jpg',
base64Image: "",
}
},
onLoad() {
},
methods: {
starClick(){
this.convertImageUrlToBase64()
},
async convertImageUrlToBase64() {
try {
this.base64Image = await imgUrlToBase64(this.imgUrl);
console.log(this.base64Image);
} catch (err) {
console.error(err);
}
},
}
}
</script>
当点击按钮时将生成如下格式:
二、将本地图片转换为base64格式
utils/imageToBase64.js
/**
* 将本地图片转换为base64格式
* @param {String} imagePath 本地图片路径
* @returns {Promise} 返回Promise对象,resolve参数为base64格式的图片数据
*/
export function imageToBase64(imagePath) {
return new Promise((resolve, reject) => {
uni.getFileSystemManager().readFile({
filePath: imagePath,
encoding: "base64",
success: (res) => {
resolve("data:image/jpeg;base64," + res.data);
},
fail: (err) => {
reject(err);
},
});
});
}
export default imageToBase64;
App.vue
<template>
<view class="content">
<button @click="starClick">点击</button>
</view>
</template>
<script>
import {
imageToBase64
} from "@/utils/imageToBase64.js";
export default {
data() {
return {
imagePath: "/static/logo.png",
base64Image: "",
}
},
onLoad() {
},
methods: {
starClick(){
this.convertImageToBase64()
},
async convertImageToBase64() {
try {
this.base64Image = await imageToBase64(this.imagePath);
console.log(this.base64Image);
} catch (err) {
console.error(err);
}
},
}
}
</script>
当点击按钮时将生成如下格式:
三、将base64格式的图片转换为图片格式
<template>
<view>
<image :src="imgSrc"></image>
</view>
</template>
<script>
export default {
data () {
return {
imgSrc: ''
}
},
onLoad() {
uni.request({
url: 'http://example.com/base64-image-data',
success: (res) => {
this.imgSrc = 'data:image/png;base64,' + res.data
}
})
}
}
</script>