网上看了很多资料,有提到用wx.arrayBufferToBase64(),在APP里面试过,不管用,uni-app里面的canvas也没有找到可以转换的方法,有没有前辈们做过类似的,可否分享一下,谢谢!
![大鼻子](https://img-cdn-tc.dcloud.net.cn/account/identicon/1945639ba06c586ef3e7755408455ae4.png)
- 发布:2018-12-13 13:58
- 更新:2019-05-23 14:49
- 阅读:19003
![大鼻子](https://img-cdn-tc.dcloud.net.cn/account/identicon/1945639ba06c586ef3e7755408455ae4.png)
大鼻子 (作者)
fileUpload() {
let _this = this;
uni.chooseImage({
count: 1,
success: res => {
uni.showLoading({
title: "上传中",
mask: true
})
this.urlTobase64(res.tempFilePaths[0]);
}
})
},
// 获取图片信息
urlTobase64(url){
const ctx = wx.createCanvasContext('canvas');
const platform = wx.getSystemInfoSync().platform
const imgWidth = 400, imgHeight=500;
ctx.drawImage(url, 0, 0, imgWidth, imgHeight);
ctx.draw(false, () => {
wx.canvasGetImageData({
canvasId: 'canvas',
x: 0,
y: 0,
width: imgWidth,
height: imgHeight,
success: res => {
// 3. png编码
let pngData = upng.encode([res.data.buffer], res.width, res.height)
// 4. base64编码
let base64 = wx.arrayBufferToBase64(pngData)
console.log('data:image/jpeg;base64,' + base64)
this.imageList.push(base64);
uni.hideLoading();
},
fail(res) {
console.log(JSON.stringify(res));
uni.hideLoading();
},
})
})
},
下载upng插件
![回梦無痕](http://img-cdn-tc.dcloud.net.cn/uploads/avatar/000/51/83/99_avatar_mid.jpg?v=0)
回梦無痕 - 暂停服务
APP可以用H5 API转
var reader = new plus.io.FileReader();
reader.onloadend = function (e) {
var speech = e.target.result;//base64图片
};
reader.readAsDataURL(file);
![BoredApe](http://img-cdn-tc.dcloud.net.cn/uploads/avatar/000/00/22/35_avatar_mid.jpg?v=1679533306)
BoredApe - 有问题就会有答案。
// 将图片转换为 Base64
handleFile(path) {
return new Promise((resolve, reject) => {
plus.zip.compressImage({
src: path,
dst: `_doc/temp/${+new Date()}.jpg`,
quality: 70,
},
({ target, size }) => {
plus.io.resolveLocalFileSystemURL(target, (file) => {
const fileReader = new plus.io.FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = ({ target: { result } }) => {
resolve(result);
};
});
},
(e) => {
reject(e);
});
});
}
是在下输了
运行成H5页面之后,这个方法还能用吗???还是这个方法只能运行在小程序环境
2019-02-22 16:26
1***@qq.com
回复 是在下输了:后面你怎么解决?我也遇到了
2019-03-10 13:17
是在下输了
@1531464644@qq.com我使用的也是楼主的方法,但是因为我这儿需要预览,这样做出来之后效果不好,后面改成文件上传,建议能文件上传就别转base64,文件上传简单快捷,转了之后各种问题
2019-03-12 17:52
是在下输了
回复 1***@qq.com:
urlTobase64(url){
const ctx = uni.createCanvasContext('canvas');
const platform = uni.getSystemInfoSync().platform
const imgWidth = 300, imgHeight=300;
ctx.drawImage(url, 0, 0, imgWidth, imgHeight);
ctx.draw(false, () => {
uni.canvasToTempFilePath({
x: 0,
y: 0,
width:imgWidth,
height:imgHeight,
canvasId: 'canvas',
quality: Number(1),
success: res => {
console.log(res);
this.imageList=res.tempFilePath;//base64
},
fail(res) {
console.log(JSON.stringify(res));
},
})
})
},
2019-03-12 17:56
1***@qq.com
his.imageList = res.tempFilePath; 获取的不是一个临时的路径地址吗,怎么可能是base64格式
2019-03-27 22:14
大小冬天
回复 是在下输了: 不好使啊
2021-03-05 19:53