写的都是啥,都是错的,正确写法已验证
imgPath 就是通过
wx.chooseImage生成的本地图片的地址(也可以用网络图片的URL,都可以)
wx.request({
url: imgPath,
method: ‘GET’,
responseType: ‘arraybuffer’,
success: function (res) {
let base64 = wx.arrayBufferToBase64(res.data);
}
})
wx.createCanvasContext配合开源库UPNG对原始图像数据进行png编码。
这位大兄弟写得很详细https://image.wxopen.club/content_ab595dea-355f-11ea-b236-a0999b08aadb.png。他使用的是腾讯AI接口,但是都是将图片数据转为base64后上传。
具体代码如下,记得引入UPNG.js和pako.min.js文件。
//画布 setCanvac: function (){ var canvasID = "mycanvas" ; var canvas = wx.createCanvasContext(canvasID) // 1. 绘制图片至canvas var imgPath = this .data.imageInfo.path; var imgWidth = this .data.imageInfo.width; var imgHeight = this .data.imageInfo.height; var arry = this .data.imageInfo.path.split( "." ); var prefix = arry[arry.length-1]; prefix = "data:image/" + prefix+ ";base64," ; var that= this ; canvas.drawImage(imgPath, 0, 0, imgWidth, imgHeight) // 绘制完成后执行回调,API 1.7.0 canvas.draw( false , () => { // 2. 获取图像数据, API 1.9.0 wx.canvasGetImageData({ canvasId: canvasID, x: 0, y: 0, width: imgWidth, height: imgHeight, success(res) { // 3. png编码 if (platform == 'ios' ) { // 兼容处理:ios获取的图片上下颠倒 res = that.reverseImgData(res) } var pngData = upng.encode([res.data.buffer], res.width, res.height); // 4. base64编码 var base64 = wx.arrayBufferToBase64(pngData); //base64 = prefix + base64;
that.upLoadImage(base64); } }) }) }, //ios图片处理 reverseImgData(res) { var w = res.width var h = res.height let con = 0 for ( var i = 0; i < h / 2; i++) { for ( var j = 0; j < w * 4; j++) { con = res.data[i * w * 4 + j] res.data[i * w * 4 + j] = res.data[(h - i - 1) * w * 4 + j] res.data[(h - i - 1) * w * 4 + j] = con } } return res },
|
wx.request({
url: ‘http://tmp/wx0009f93430dceb3f.o6zAJsxyeFeUYvzbJ8nfjdv2mRzc.4LgpJVDaSB9kda92809aa6220fb9bf3.png’,
method: ‘GET’,
responseType: ‘arraybuffer’,
success: function (res) {
console.log(res);
let base64 = wx.arrayBufferToBase64(res.data);
console.log(base64);
}
});