uniapp微信小程序以及H5上传图片压缩问题利用canvas绘制图片之后再转成图片

html部分

<canvas canvas-id="canvas" id="canvas"  
        style="position:absolute;left:-10000px;top:-10000px"
        :style="{width:cWidth+'px',height:cHeight+'px'}"></canvas>

 js部分:

data() {
    return {
        cWidth:0,
        cHeight:0
    }
  },

method:{

      chooseImage(){

                uni.chooseImage({   //选择照片或者时拍照上传
                        count: num, 
                        sizeType: ['original', 'compressed'],
                        sourceType: ['camera'],
                        success: res=>{
                            const tempFilePaths = res.tempFilePaths
                            // #ifdef H5
                                    this.recursionCompressH5(tempFilePaths[0],res=>{
                                    this.upLoadImgs(res)
                            })
                            // #endif
                    
                            // #ifndef H5
                            this.recursionCompressMP(tempFilePaths[0],res=>{
                                    this.upLoadImgs(res)
                            })
                            // #endif
                        }
                    });

        } ,

recursionCompressMP(url, callback) {
            let that = this;
            uni.getImageInfo({
                src: url,
                success (res) {
                    var originWidth, originHeight;
                  originHeight = res.height;
                  originWidth = res.width;
                  console.log(originWidth);
                 
                  //压缩比例
                  // 最大尺寸限制
                  var maxWidth = 750,
                    maxHeight = 1200;
                  // 目标尺寸
                  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));
                    }
                  }
                  
                  that.cWidth = targetWidth
                  that.cHeight = targetHeight
                  
                  var ctx = uni.createCanvasContext('canvas')
                  ctx.drawImage(res.path, 0, 0, that.cWidth, that.cHeight)
                  ctx.draw(false, setTimeout(() => {
                      uni.canvasToTempFilePath({
                          canvasId: 'canvas',
                          destWidth: that.cWidth,
                          destHeight: that.cHeight,
                          fileType: 'jpg',
                          quality: 0.4,
                          success: function(res1) {
                              callback && callback(res1.tempFilePath)                    
                          },
                          fail: function(res) {
                              console.log(res.errMsg)
                          }
                      })
                  }, 100))
                },
            })
        },
        recursionCompressH5(url, callback) {
            let indexObj = this;
            uni.getImageInfo({
                src: url,
                success(res) {
                    let canvasWidth = res.width;
                    let canvasHeight = res.height;
                    let img = new Image();
                    img.src = res.path;
                    let canvas = document.createElement("canvas");
                    let ctx = canvas.getContext("2d");
                    canvas.width = canvasWidth / 2;
                    canvas.height = canvasHeight / 2;
                    ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
                    canvas.toBlob(function (fileSrc) {
                        let imgSrc = window.URL.createObjectURL(fileSrc);
                        uni.getFileInfo({
                            filePath: imgSrc,
                            success:(resFileInfo) => {
                                if (resFileInfo.size > 1024 * 1024) {
                                    indexObj.recursionCompressH5(imgSrc, callback);
                                    return;
                                } else {
                                    callback && callback(imgSrc)
                                }
                            },
                        });
                    });
                }
            });
        },

upLoadImgs(path,type){
            console.log(path);
            uni.showLoading({
                title:'上传中'
            })
            uni.uploadFile({
                url:"https://wandianhuolian.ncltkj.com/"+this.$api.upLoad.upLoad,
                filePath: path,
                header:{
                    'Authorization' : "Bearer " + uni.getStorageSync('token'),
                },
                name:'upload',
                success:resp=>{
                    uni.hideLoading()
                    if(resp.statusCode == 200){
                        const data = JSON.parse(resp.data)
                        console.log(data);
                    }else{
                        uni.showToast({
                            title:'上传失败',
                            icon:'none',
                            duration:1500
                        })
                    }
                }
            })
            
        }

} 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Uniapp中,实现微信小程序分享图片的流程如下: 1. 首先,使用canvas绘图功能将图片绘制到页面上,并生成一个本地路径。 2. 接下来,将绘制好的图片保存至本地。 3. 最后,由用户自行选择将保存的图片分享给朋友或者朋友圈。 除了以上方法,还可以使用mixins文件夹下的share.js文件来定义全局分享内容。在该文件中,可以设置分享的标题、路径、图片链接和描述。然后,通过onShareAppMessage方法实现发送给朋友的分享,通过onShareTimeline方法实现分享到朋友圈的分享。 总结起来,Uniapp微信小程序分享图片的流程包括使用canvas绘图生成本地路径、保存图片至本地、由用户自行分享图片,以及使用全局分享设置进行自定义分享。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [uniapp小程序分享图片](https://blog.csdn.net/m0_49744220/article/details/125769297)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [uniapp 实现微信小程序分享给好友、朋友圈](https://blog.csdn.net/weixin_38982591/article/details/125096377)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值