微信小程序使用wx.chooseImage上传图片时进行压缩,并添加时间水印

在微信小程序的开发过程,经常会使用自带的api(wx.chooseImage)进行图片拍照或选择图片进行上传,有时图片太大,造成上传和下载时过慢,现对图片进行压缩后上传,以下是流程和代码

一、小程序的版本选择了3.2.5,使用其它版本有时不知道错误

二、wxml代码,需要添加canvas

<canvas style="width: {{cwidth}}px;height: {{cheight}}px;position:fixed;top:9999px" canvas-id="mycanvas"></canvas>

三、js代码

1、参数

cwidth:'375',

cheight:'667',

//上传图片时,当前数组下标,用来确认上传第几张图片,上传完一次就+1

tempNum: 0,

// 图片上传参数

filePath: "",

images: [],

count: 1,

2、选择图片wx.chooseImage

复制代码
// 选择图片
    chooseImage: function (e) {
        console.log('选择图片chooseImage')
        var that = this;
        wx.chooseImage({
            count: that.data.count, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有
            success: function (res) {
                console.log('图片大小='+res.tempFiles[0].size)
                if(res.tempFiles[0].size>500000){//图片大于500K才进行压缩,压缩后大约400K
                    that.canvasImage(res.tempFilePaths[0], 0) 
                } else{
                    //图片添加水印
                    that.addTimeWatermark(res.tempFilePaths[0])
                } 
            },
        })
    },

//压缩图片
     canvasImage:function(imgUrl,index){
         console.log('canvasImage压缩图片')
        wx.showLoading({
            title: '照片上传中...',
          })
        var that = this
        wx.getImageInfo({
            src: imgUrl,
            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 ? 540 : 810,
                    maxHeight = originWidth >= originHeight ? 810 : 540;
                // 目标尺寸
                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) => {
                            wx.hideLoading()
                            console.log("压缩后的临时路径:", res.tempFilePath)
                            that.addTimeWatermark(res.tempFilePath)
                        },
                        fail: (err) => {
                            wx.hideLoading()
                            console.error(err)
                        }
                    }, this)
                }, 400); //延迟400毫秒为了等canvas画上
            }
        })
    },
// 添加时间水印
    addTimeWatermark: function (imagePath) {
        var that = this
        console.log('addTimeWatermark=' + imagePath)
        var ctx = wx.createCanvasContext('mycanvas');
        this.roundRectColor(ctx, 0, 30, 375, 620, 16);
        ctx.drawImage(imagePath, 15, 120, 344, 400);
        ctx.save();

        // 设置水印文字
        const time = app.util.formatTime()
        console.log('time=' + time)
        ctx.beginPath(); //开始绘制   
        ctx.setFontSize(22);
        ctx.setFillStyle('#DC3545')
        ctx.fillText(time, 15, 450); // 根据实际情况调整位置
        ctx.draw();

        //将生成好的图片保存到本地,需要延迟一会,绘制期间耗时
        setTimeout(function () {
            wx.canvasToTempFilePath({
                canvasId: 'mycanvas',
                success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    console.log('imagePath=' + tempFilePath)
                    that.data.images.push(tempFilePath);
                    console.log(that.data.images)
                    that.setData({
                        imagePath: tempFilePath,
                        images: that.data.images
                    });
                },
                fail: function (res) {
                    console.log(res);
                }
            });
        }, 200);

    },
    roundRectColor: function (context, x, y, w, h, r) { //绘制圆角矩形(纯色填充)
        context.save();
        context.setFillStyle("#FFFFFF"); //小框
        context.setStrokeStyle('#FFFFFF') //大框
        // context.setLineJoin('round'); //交点设置成圆角
        context.setLineWidth(r);
        context.strokeRect(x + r / 2, y + r / 2, w - r, h - r);
        context.fillRect(x + r, y + r, w - r * 2, h - r);
        context.stroke();
        context.closePath();
    },
//上传图片
app.util.uploadImg(that.callBackClose, app, that.data.pid, that.data.images, that.data.tempNum, 'check')
相关推荐
说私域4 小时前
公域流量向私域流量转化策略研究——基于开源AI智能客服、AI智能名片与S2B2C商城小程序的融合应用
人工智能·小程序
半生过往4 小时前
微信小程序文件下载与预览功能实现详解
微信小程序·小程序·notepad++·压缩包下载解压
源码_V_saaskw4 小时前
JAVA图文短视频交友+自营商城系统源码支持小程序+Android+IOS+H5
java·微信小程序·小程序·uni-app·音视频·交友
weixin_lynhgworld7 小时前
淘宝扭蛋机小程序系统开发:重塑电商互动模式
大数据·小程序
996幸存者9 小时前
uni-app区域选择、支持静态、动态数据
微信小程序·uni-app
ᥬ 小月亮10 小时前
Uniapp编写微信小程序,绘制动态圆环进度条
微信小程序·小程序·uni-app
The_era_achievs_hero17 小时前
UniappDay03
vue.js·微信小程序·uni-app
说私域20 小时前
技术赋能与营销创新:开源链动2+1模式AI智能名片S2B2C商城小程序的流量转化路径研究
人工智能·小程序·开源
游戏开发爱好者81 天前
没有 Mac,如何上架 iOS App?多项目复用与流程标准化实战分享
android·ios·小程序·https·uni-app·iphone·webview
weixin_lynhgworld1 天前
代驾小程序系统开发:引领出行行业数字化转型
小程序