微信小程序压缩图片并上传

微信小程序压缩图片

1.wxml

<canvas class="canvas" style="width: {{cw0}}px; height: {{ch0}}px;" canvas-id="myCanvas0"></canvas>

2.js

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		scale: 0.5,
		cw0: "",
		ch0: ""
	},
	compress: function(e) {
		let that = this;
		wx.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['camera'],
			success(res) {
				let path = res.tempFilePaths[0];
				let size = res.tempFiles[0].size / 1024;
				if (size > 100) { //大于100k压缩
					wx.getImageInfo({
						src: path,
						success(res) {
							//console.log('获得原始图片大小',res.width)
							let originWidth, originHeight;
							originHeight = res.height;
							originWidth = res.width;
							console.log(originWidth);
							//压缩比例
							// 最大尺寸限制
							let maxWidth = originWidth * that.data.scale,
								maxHeight = originHeight * that.data.scale;
							// 目标尺寸
							let 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));
								}
							}
							//更新canvas大小
							that.setData({
								cw0: targetWidth,
								ch0: targetHeight
							});
							let id = "myCanvas0";
							//尝试压缩文件,创建 canvas
							let ctx = wx.createCanvasContext(id);
							ctx.clearRect(0, 0, targetWidth, targetHeight);
							ctx.drawImage(path, 0, 0, targetWidth, targetHeight);
							ctx.draw();
							wx.showLoading({
								title: "压缩中..."
							})
							//保存图片
							setTimeout(function() {
								wx.canvasToTempFilePath({
									fileType: "jpg",
									canvasId: id,
									success: (res) => {
										//写入图片数组
										let uploadFile = res.tempFilePath;
										that.uploadImg(uploadFile);
										wx.hideLoading()
									},
									fail: (err) => {
										console.error(err)
									}
								}, this)
							}, 500);
						}
					})
				} else {
					that.uploadImg(path);
				}
			}
		})
	},
	uploadImg: function(imgPath) {
		let that = this;
		let urlStr = "";//上传地址
		wx.uploadFile({
			url: urlStr,
			filePath: imgPath,
			name: "file",
			success: function(res) {
				
			},
			fail: function(err) {
				
			}
		});
	}
})

3.wxss

.canvas {
	position: absolute;
	left: -4000px;
}

隐藏canvas

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Let dreams fly

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

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

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

打赏作者

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

抵扣说明:

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

余额充值