微信小程序里自己处理图片写起来比较麻烦,一些标准的可以参数化的处理如果能调用万象优图来处理就轻松多了。虽然微信云开发的“云存储”从腾讯云COS里面看不到相应的桶,但它背后其实还是一个COS桶,所以只要给文件生成临时访问路径,万象优图的api也可以直接在微信云开发里面调用,像这样:
代码语言:javascript复制chooseImage(){
random=Math.random().toString();//随机文件名
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success (res) {
// tempFilePath可以作为img标签的src属性显示图片
var tmpUrl = res.tempFilePaths[0]
getCurrentPages()[0].setData({"imgSrc":tmpUrl})
wx.cloud.uploadFile({//上传到微信云开发的云存储
cloudPath: random,
filePath: tmpUrl, // 文件路径
success: res => {
// get resource ID
fileIDs = [res.fileID];
wx.cloud.getTempFileURL({ //获取临时文件名
fileList:fileIDs,
success:res=>{
wx.request({
url:res.fileList[0].tempFileURL "?imageAve", //通过临时文件名调用万象优图的imageAVe接口
success:(res)=>{
var sRGB = res.data.RGB.substr(2);
getCurrentPages()[0].setData({"avgColor2":"#" sRGB})
var rgb=[
parseInt(sRGB.substr(0,2),16),
parseInt(sRGB.substr(2,2),16),
parseInt(sRGB.substr(4,2),16)
]
var hsv = rgbToHsv(rgb);
getCurrentPages()[0].setData({"avgColor1":"rgb(" hsvToRgb([hsv[0]*1,hsv[1]*1,hsv[2]*0.8]).join() ")"});
getCurrentPages()[0].setData({"avgColor3":"rgb(" hsvToRgb([hsv[0]*1,hsv[1]*1,hsv[2]*1.25]).join() ")"});
wx.cloud.deleteFile({ //删除临时文件
fileList: fileIDs,
success: res => {
console.log("临时文件已删除")
}
})
},
fail:(err)=>{
console.log(err)
}
})
}
})
},
fail: err => {
console.log(err)
// handle error
}
})
}
})
}
为了加工颜色,调用了两个颜色转换的函数:
代码语言:javascript复制function rgbToHsv(arr) {
var h = 0, s = 0, v = 0;
var r = arr[0], g = arr[1], b = arr[2];
arr.sort(function (a, b) {
return a - b;
})
var max = arr[2]
var min = arr[0];
v = max / 255;
if (max === 0) {
s = 0;
} else {
s = 1 - (min / max);
}
if (max === min) {
h = 0;//事实上,max===min的时候,h无论为多少都无所谓
} else if (max === r && g >= b) {
h = 60 * ((g - b) / (max - min)) 0;
} else if (max === r && g < b) {
h = 60 * ((g - b) / (max - min)) 360
} else if (max === g) {
h = 60 * ((b - r) / (max - min)) 120
} else if (max === b) {
h = 60 * ((r - g) / (max - min)) 240
}
h = parseInt(h);
s = parseInt(s * 100);
v = parseInt(v * 100);
return [h, s, v]
}
function hsvToRgb(arr) {
var h = arr[0], s = arr[1], v = arr[2];
s = s / 100;
v = v / 100;
var r = 0, g = 0, b = 0;
var i = parseInt((h / 60) % 6);
var f = h / 60 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i) {
case 0:
r = v; g = t; b = p;
break;
case 1:
r = q; g = v; b = p;
break;
case 2:
r = p; g = v; b = t;
break;
case 3:
r = p; g = q; b = v;
break;
case 4:
r = t; g = p; b = v;
break;
case 5:
r = v; g = p; b = q;
break;
default:
break;
}
r = parseInt(r * 255.0)
g = parseInt(g * 255.0)
b = parseInt(b * 255.0)
return [r, g, b];
}
回调有点深,因为wx.request 不支持promise风格,又不想混着风格写。