借鉴了网上的代码,使用画布,将图像重绘后,保存。试了两种保存方法,都返回空白图片。基础库:2.21.4
WXML:
JS: (确定了传入的img_src是对的,在开发者工具里似乎把本地图片链接都转为http链接了)
var that = this;
wx.getImageInfo({
src: img_src,
success(res){
//---------利用canvas压缩图片--------------
var canvasHeight =300;
var canvasWidth = 400;
that.setData({
cHeight: canvasHeight,
cWidth: canvasWidth
});
wx.createSelectorQuery()
.select('#myCanvas') // 在 WXML 中填入的 id
.fields({ node: true, size: true })
.exec((res) => {
// Canvas 对象
const canvas = res[0].node
// Canvas 画布的实际绘制宽高
const renderWidth = res[0].width
const renderHeight = res[0].height
// Canvas 绘制上下文
const ctx = canvas.getContext('2d')
// 初始化画布大小
const dpr = wx.getWindowInfo().pixelRatio
canvas.width = renderWidth * dpr
canvas.height = renderHeight * dpr
ctx.scale(dpr, dpr)
var img = canvas.createImage();
img.src= img_src;
ctx.drawImage(img, 0, 0,canvasWidth,canvasHeight)
//下面是两种保存方法,
wx.canvasToTempFilePath({
canvas: canvas,
success(res){
that.setData({
temp: res.tempFilePath
})
_img = res.tempFilePath;
console.log("chenggong")
},
fail(res){
console.log("shibai")
console.log(res.data)
}
})
const path = canvas.toDataURL("image/jpeg", 0.7) //返回值是一个数据url,是base64组成的图片的源数据、可以直接赋值给图片的src属性
that.setData({
base64_img: path,
base64: true
})
console.log(path)
})
}
})
https://developers.weixin.qq.com/s/abDja2mq7oCa
补充代码片段
改动了一下你的代码:
<canvas canvas-id="myCanvas" style="width:{{cWidth}}px;height:{{cHeight}}px;position: absolute;left:-1000px;top:-1000px;"/>
bindUpload() {
//要加图片压缩功能
var that = this;
wx.chooseMedia({
count: 1,
mediaType: ["image"],
sourceType: ["album", "camera"],
sizeType: ['compressed'],
camera: "front",
success(res) {
that.setData({
imagePath: res.tempFiles[0].tempFilePath
})
// that.compress_img(res.tempFiles[0].tempFilePath);
var ctx = wx.createCanvasContext('myCanvas')
ctx.drawImage(res.tempFiles[0].tempFilePath, 0, 0, 400, 400)
ctx.draw(false, () => {
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
fileType: "jpg",
quality: 0.7,
success(res) {
console.log(res.tempFilePath);
}
})
})
},
fail() {
wx.showToast({
title: "图片选择失败",
icon: "none",
duration: 2000
})
}
})
},
若只是为了压缩,用wx.compressImage更方便,没必要canvas
img.onload = (e) => {
ctx.drawImage(img, 0, 0,canvasWidth,canvasHeight)
}
setTimeout(function(){
wx.canvasToTempFilePath({
canvas: canvas,
fileType: "jpg",
quality: 0.7,
success(res){
that.setData({
temp: res.tempFilePath
})
_img = res.tempFilePath;
console.log("chenggong")
},
fail(res){
console.log("shibai")
console.log(res.data)
}
})
},1000)
没那么复杂,canvasToTempFilePath中添加两个参数即可。 wx.canvasToTempFilePath ... fileType: 'jpg', quality: 0.7,