思路:选择图片,在上传图片之前,对图片进行压缩
方法:canvas
准备:
腾讯云cos:
注册对象存储cos的账户 – 创建存储桶 – 获取SecretId 和 SecretKey – 在存储桶的基本配置里面将你的本地的地址添加进跨域的白名单里,这样本地就不会跨域(注:是你的本地IP地址,不是localhost)
下载cos的js文件:
方式一:https://github.com/tencentyun/cos-wx-sdk-v5/blob/master/demo/lib/cos-wx-sdk-v5.js 到这里去把cos-wx-sdk-v5.js文件下载到自己的项目里面
方式二:npm install cos-wx-sdk-v5
引用刚刚下载的js:var COS = require('cos-wx-sdk-v5')
小程序实现:
html/css:
.canvas-box {
position: fixed;
top: 999999rpx;
left: 0
}
<view class="canvas-box">
<canvas style="background:#f1f1f1;width: {
{imageSize.imageWidth}}px; height: {
{imageSize.imageHeight}}px;" canvas-id="myCanvas" />
</view>
js:
let that = this;
wx.chooseImage({
sizeType: ['original'],
count: '图片数量',
sourceType: ['album', 'camera'],
success(res) {
wx.showLoading({
title: '上传中',
mask: true
});
const tempFilePaths = res.tempFilePaths;
that.getCanvasImg(0, tempFilePaths)
}
})
getCanvasImg(index, tempFilePaths) {
var that = this;
if (index < tempFilePaths.length) {
const ctx = wx.createCanvasContext(`myCanvas`);
*//微信小程序的drawImg需要网络路径的图片,所以转了一下*
wx.getImageInfo({
src: tempFilePaths[index],
success: res1 => {
console.log(res1, '获取要画的图片')
const imageSize = this.imageUtil(res1)
this.imageSize = imageSize
console.log(imageSize, 123)
let destWidth = res1.width
let destHeight = res1.height
this.$apply(() => {
ctx.restore()
ctx.drawImage(res1.path, 0, 0, res1.width, res1.height, 0, 0, imageSize.imageWidth, imageSize.imageHeight)
ctx.draw()
})
//保存图片,canvas需要时间画画
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: