将图片存储到数据库的基本思路:前端选取图片,将图片转换为base64格式存放于数组中,后续可用数组的join()方法,以#作为连接,将其转换为字符串存放到数据库
这样,需要从数据库获得图片时,只需将请求到的字符串用split方法转换为数组,遍历显示出图片
<template>
<view class="content">
<button @click="imgchoose()">选择图片</button>
<button type="default" @click="getBase64Image()">转换</button>
<image v-for="(item,index) in imgbase64" :key=index :src=item mode=""></image>
</view>
</template>
<script>
export default {
data() {
return {
imgpath : [],
tag : 0,
imgbase64 : [] //该数组用于存放转换后的base64图片
}
},
onLoad() {
},
methods: {
imgchoose(){
var that = this
uni.chooseImage({ //uni官方api,用于选取本地图片
count: 6, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: function (res) {
that.imgpath = res.tempFilePaths //先获得本地文件的路径列表,存储到数组
console.log(that.imgpath) //注意该api会将路径转换为blob格式
}
})
},
getBase64Image(){ //调用工具方法,遍历路径数组,全部转换为base64
console.log(" 开始转换")
var that = this
for(let i=0;i<that.imgpath.length;i++){
var url = that.imgpath[i]
getImgToBase64(url,function(dataURL){
console.log(dataURL)
that.imgbase64.push(dataURL)
})
}
console.log(that.imgbase64)
function getImgToBase64(url,callback){//将图片转换为Base64的工具方法
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL('image/png');
callback(dataURL);
canvas = null;
};
img.src = url;
}
}
}
}
</script>