博主信息
弘德誉曦的博客
博文
137
粉丝
1
评论
0
访问量
115772
积分:1
P豆:431

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

2021年09月27日 22:35:54阅读数:68博客 / 弘德誉曦的博客/ js笔录

wxml写入

1
2
3
<view bindtap='uploadImg'>上传</view>
 <image bindtap='uploadImg' data-number="0" src="{{ uploadPic[0] }}" alt="" mode="widthFix"></image>
<canvas style="width: {{cw}}px; height: {{ch}}px;" canvas-id="firstCanvas"></canvas>

  

JS参考

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
uploadImg(e) {
   let that = this;
   console.log(e);
   let index = e.currentTarget.dataset.number;
   let uploadFile = ''//最后处理完,图片上传的图片地址
   wx.chooseImage({
     success(res) {
       console.log(res)
       const tempFilePaths = res.tempFilePaths;
 
       //获得原始图片大小
       wx.getImageInfo({
         src: res.tempFilePaths[0],
         success(res) {
           // console.log('获得原始图片大小',res.width)
           //console.log(res.height)
           var originWidth, originHeight;
           originHeight = res.height;
           originWidth = res.width;
           console.log(originWidth);
           //压缩比例
           // 最大尺寸限制
           var maxWidth = 1200,
             maxHeight = 600;
           // 目标尺寸
           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));
             }
           }
           //尝试压缩文件,创建 canvas
           var ctx = wx.createCanvasContext('firstCanvas');
           ctx.clearRect(0, 0, targetWidth, targetHeight);
           ctx.drawImage(tempFilePaths[0], 0, 0, targetWidth, targetHeight);
           ctx.draw();
           //更新canvas大小
           that.setData({
             cw: targetWidth,
             ch: targetHeight
           });
           //保存图片
           setTimeout(function() {
             wx.canvasToTempFilePath({
               canvasId: 'firstCanvas',
               success: (res) => {
                 //写入图片数组
                 var uploadpic = "uploadPic[" + index + "]";
                 //
                 that.setData({
                   [uploadpic]: res.tempFilePath
                 });
                 uploadFile = res.tempFilePath;
                 //保存到相册
                 // wx.saveImageToPhotosAlbum({
                 //   filePath: res.tempFilePath,
                 //   success: (res) => {
                 //     console.log(res)
                 //   },
                 //   fail: (err) => {
                 //     console.error(err)
                 //   }
                 // })
                 wx.uploadFile({
                   url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
                   filePath: uploadFile,
                   name: 'file',
                   formData: {
                     'user''test'
                   },
                   success(res) {
                     const data = res.data
                     //do something
                   }
                 })
               },
               fail: (err) => {
                 console.error(err)
               }
             }, this)
           }, 500);
 
 
 
 
         }
       })
 
 
 
 
     }
   })
 }

  

后面还有一个写法 20210703

 

 // 上传图片
  async chooseImg() {
    var _that = this;
    const imgs = this.data.imgs;
    const max_imgs_length = 1;
    var oldCount = imgs.length;
    const tempFilePaths = await this.$chooseImage(max_imgs_length, ['original']);

    for (var i = 0; i < tempFilePaths.length; i++) {
      // imgs.push(tempFilePaths[i]); 
      var tfp = tempFilePaths[i];
       
      //获得原始图片大小
      wx.getImageInfo({
        src: tfp,
        success(res) {

          var originWidth, originHeight;
          originHeight = res.height;
          originWidth = res.width;
          console.log(originWidth);
          //压缩比例
          // 最大尺寸限制
          var maxWidth = 1200,
            maxHeight = 1000;
          // 目标尺寸
          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.setData({
            cw: targetWidth,
            ch: targetHeight
          });

          //尝试压缩文件,创建 canvas
          var ctx = wx.createCanvasContext('ssd');
          ctx.clearRect(0, 0, targetWidth, targetHeight);
          ctx.drawImage(tfp, 0, 0, targetWidth, targetHeight);
          ctx.draw(false, setTimeout(function () { 
            wx.canvasToTempFilePath({
              canvasId: 'ssd',
              fileType:'jpg',
              destWidth:targetWidth,
              destHeight:targetHeight,
              quality:1.0,
              success: (r) => { 
                imgs.push(r.tempFilePath);
                _that.setData({
                  imgs: imgs
                });
               _that.loadPhoto(oldCount);
              },
              fail: (err) => {
                console.error(err)
              }
            }, this)
          }, 500));
          //保存图片 
        }
      })
    } 
  }
 
 
前端隱藏canvas
  <view  style="position:fixed;top:999999999999999999999rpx;">
    <canvas id="ssd" canvas-id="ssd" style="width:{{cw}}px;height:{{ch}}px;"></canvas>
    </view>

版权申明:本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!

全部评论

文明上网理性发言,请遵守新闻评论服务协议

条评论
  • --通过canvas生成保存到本地
    识字中取字的方法:首先打开,点击“发现”;然后搜索查找识字点击开始拍摄;接着选择好点击全选;最后选择好文字后,点左下角的“复制文字”后就可以在文档里进行粘贴了
    审核拒绝,拒绝原因是用户可能存在违法违规问题,必须有审核机制。解决方法如下:config.json云函数和js。
    提取的链接方法:首先关联自建一个文;然后点击添加【】,打开找到;接着进入提取链接的页面,点击右角【...】按钮;最后点击【复制本页面路径】即可。
    可以被收藏。
    中,要显示一张,有两种加载方式:加载本地和加载网络。加载网络在加载网络这方面封装的还是很好的,包括语音和视频的加载。直接给src这个属性附地址,它会自动加载。
    css sprite优缺点是:1、减少HTTP请求数,极大地提高页面加载速度;2、增加息重复度,提高比,减少;3、更换风格方便,只需在一张或几张修改颜色或样式即可实现;4、麻烦
    实现在电脑玩的方法:首先找到开发者选项打开USB调试;然后在电脑安装“total_control”;最后选择“输文件”即可。
    BMP格式的是无损保存,质量最好,最清楚;但文件大输慢,而不适用于网络应用。其他都是有所,保存后会有一定度的像素丢失,但文件输快,适于网络的应用。
    解决无法显示的办法:首先给标签元素设置背景;然后通过image标签查验一下的路径;接着当本地资源无法通过 WXSS 获取时,就使用【background-image】方法;最后删除
    是2011年1月21日线的,是腾讯公司推出的一个为智能终端提供即时通讯服务的免费应用 ,由张龙所带领的腾讯广州研发中心产品团队打造 ;支持跨通运营商、跨操作系统平台通过网络快速发送免费语音短
    在uni-app项目中使用iconfont提供的标字体库,美化页面;实现自定义组件,且可以自定义属性和实现父子组件之间的消息递;预览和真机测试,APP端云打包和本地打包。
    方法:1、打开点击发现,再点击;2、在搜索框中输入“好友位置定位器”点击;3、点击页面下方的“开始获取好友位置”,在弹窗中设定标题和,点击继续进行下一步;4、点击“发送给好友”,在弹窗中选择要发送的好友