微信小程序实现图片压缩上传(base64格式)

1.从本地相册或者相机拍照选择图片;

chooseImage (){
	wx.chooseImage({
 	 	count: 1,
 	 	//图片尺寸原图和压缩图
  		sizeType: ['original', 'compressed'],
  		//从相册选图和使用相机
  		sourceType: ['album', 'camera'],
  		success (res) {
    		// tempFilePath可以作为img标签的src属性显示图片
    		const tempFilePaths = res.tempFilePaths
  		}
	})
}

2.将图片转换为base64格式;

//img_url为选择图片得到的临时路径
imgBase64(img_url) {
        let res = wx.getFileSystemManager().readFileSync(img_url, 'base64')
        console.log("输出base64",res)
        return res
    },

3.将图片上传;

upLoad(){
	wx.request({
  		url: '你的接口', 
  		data: {
   			img:'',//转base64后的字符串
  		},
 		 header: {
   		 'content-type': 'application/json' 
  		},
  		success (res) {
    		console.log(res.data)
  		}
	})
}

但在实际开发中,用户上传的图片有可能很大,上传时间就会变长,这样就会影响用户体验,这个时候就需要我们对图片进行压缩。本文采用canvas压缩图片,步骤如下:

  • 创建canvas;
  • 取得图片临时路径;
  • 取得图片的原始尺寸;
  • 对图片原始尺寸进行等比例缩放;
  • 将缩放后的图片画到canvas上;
  • 导出canvas画出的图片资源url;
  • 将url转为base64上传;

创建canvas,注意canvas标签中对于id的定义(刚开始尝试了2d写法,在画图片时候失败了)

//wxml
<canvas   style="width: {{cwidth}}px;height: {{cheight}}px;" canvas-id="mycanvas" class="canvas-compress"></canvas>

//js
data:{
	cwidth:'',
	cheight:'',
}

//wxss
//此处是为了保证画出的图片不出现在视野中
.canvas-compress {
	position: absolute;
	top: -1000px;
	background-color: gray;
}

压缩画出canvas,得到临时路径:

 get_img(url) {
        let that = this
        console.log("选择图片返回的路径", url)
        wx.getImageInfo({
            src: url,
            success(res) {
                console.log("路径", res.path)
                console.log('获得原始图片大小', res.width, res.height)
                var originWidth, originHeight;
                originHeight = res.height;
                originWidth = res.width;
                // 最大尺寸限制   //压缩比例
                var maxWidth = originWidth >= originHeight ? 300 : 600,
                    maxHeight = originWidth >= originHeight ? 600 : 300;
                // 目标尺寸
                var targetWidth = originWidth,
                    targetHeight = originHeight;
                //等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
                if (originWidth > maxWidth || originHeight > maxHeight) {
                    if (originWidth / originHeight > maxWidth / maxHeight) {
                        // 要求宽度*(原生图片比例)=新图片尺寸
                        targetWidth = maxWidth;
                        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                    } else {
                        targetHeight = maxHeight;
                        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                    }
                }
                console.log("压缩后的图片大小", targetWidth, targetHeight)
                var ctx = wx.createCanvasContext('mycanvas');
                ctx.clearRect(0, 0, targetWidth, targetHeight);
                ctx.drawImage(res.path, 0, 0, targetWidth, targetHeight);
                ctx.draw();
                //更新canvas大小
                that.setData({
                    cwidth: targetWidth,
                    cheight: targetHeight
                });
                setTimeout(function () {
                    wx.canvasToTempFilePath({
                        canvasId: 'mycanvas',
                        success: (res) => {
                            console.log("压缩后的临时路径:", res.tempFilePath)
                        },
                        fail: (err) => {
                            console.error(err)
                        }
                    }, this)
                }, 400); //延迟400毫秒为了等canvas画上
            }
        })
    },
  • 7
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失忆症患者_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值