微信公众号网页开发,使用微信JS-SDK选择图片。
npm 方式安装的jssdk,"weixin-js-sdk": "^1.6.0",
1 调用选择图片api,Android真机公众号选择的图片是压缩后的,比如选了一张2149*1373分辨率的图片,返回的图片分辨率640*400左右。
2 微信电脑端,公众号选择图片就能正常返回原图。
相关选择图片代码:
selectCardface: function() {
var that = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
console.log(res);
var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
var faceImgPath = localIds[0];
console.log('imgPath:' + faceImgPath);
that.checkImg(faceImgPath);
},
});
},
checkImg: function(imgPath) {
let that = this;
wx.getLocalImgData({
localId: imgPath, // 图片的localID
success: function(res) {
var localData = res.localData;
if (localData.indexOf('data:image') != 0) {
//判断是否有这样的头部
localData = 'data:image/jpeg;base64,' + localData
}
localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg')
//第一个替换的是换行符,第二个替换的是图片类型,因为在IOS机上测试时看到它的图片类型时jgp,
//这不知道时什么格式的图片,为了兼容其他设备就把它转为jpeg
let image = new Image();
let w, h;
image.src = localData;
// 如果有缓存,读缓存
// if (image.complete) {
// w = image.width; // 图片宽度
// h = image.height; // 图片高度
// } else { //否则加载图片
// }
image.onload = function() {
w = image.width; // 图片宽度
h = image.height; // 图片高度
image.onload = null; // 避免重复加载
if (w > that.imgWlimit && h > that.imgHlimit) {
let imgSize = that.getImgSize(localData);
console.log("图片宽高:" + w + "*" + h);
console.log("图片大小:" + (imgSize / 1024) + "KB");
if (imgSize > that.imgSizeLimit) {
that.errorMsg = "图片大小不能超过10MB";
that.showErrorMsg();
} else {
that.toEditCardface(imgPath);
}
} else {
that.errorMsg = "图片像素不符合要求,图片的像素:" + w + "*" + h
that.showErrorMsg();
}
};
}
});
},
getImgSize: function(imgBase64) {
//1.需要计算文件流大小,首先把头部的data:image/png;base64,(注意有逗号)去掉。
var str = imgBase64.split(",")[1];
//2.找到等号,把等号也去掉
var equalIndex = str.indexOf('=');
if (str.indexOf('=') > 0) {
str = str.substring(0, equalIndex);
}
//3.原来的字符流大小,单位为字节
var strLength = str.length;
//4.计算后得到的文件流大小,单位为字节
var fileLength = parseInt(strLength - (strLength / 8) * 2);
return fileLength;
},