小程序使用原生的camera组件拍照压缩上传示例
发布于 5 年前 作者 xia69 3434 次浏览 来自 分享

wxml文件:
<view>
<!–相机组件–>
<camera device-position=’{{status}}’ model=‘normal’ flash=‘off’ style=‘width:{{w}}px;height:{{h}}px’ binderror=‘error’>

&lt;cover-view style="position:absolute" hidden='{{hideTakeButton}}' bindtap='test'&gt;
    &lt;button type='primary' plain='true'&gt;测试&lt;/button&gt; 
&lt;/cover-view&gt;

&lt;!--头像框--&gt;
&lt;cover-view style="position:absolute;width:100%;height:{{h}}px;z-index:-99" hidden='{{hideMask}}'&gt;
  &lt;cover-image src='{{config.imgBasePath}}/img/face_mask.png'&gt;&lt;/cover-image&gt;
&lt;/cover-view&gt; 

&lt;!--拍摄按钮--&gt;
&lt;cover-view style="position:absolute;bottom:17%;left:{{(w-66)/2}}px;" hidden='{{hideTakeButton}}' bindtap='takePhoto'&gt;
  &lt;cover-image src='{{config.imgBasePath}}/img/takephoto_take.png'style="width:132rpx;"&gt;&lt;/cover-image&gt;
&lt;/cover-view&gt;

&lt;!--定格图片--&gt;
&lt;cover-view style='position:absolute;width:100%;height:{{h}}px;z-index:-1' hidden='{{hideCoverImage}}'&gt;
  &lt;cover-image src="{{showPath}}"&gt;&lt;/cover-image&gt;
&lt;/cover-view&gt;

&lt;!--重拍按钮--&gt;
&lt;cover-view class="complete" hidden='{{hideCoverButton}}'&gt;
    &lt;button class="reset" bindtap='takeAgain'&gt;重拍&lt;/button&gt;
    &lt;button class="submit" bindtap='confirm'&gt;完成&lt;/button&gt;
&lt;/cover-view&gt;

</camera>
<!-- <view style=“position:fixed;top:999999999999999999999rpx;”>
<canvas style=“width:{{cw}}px;height:{{ch}}px;” canvas-id=‘firstCanvas’>
</canvas>
</view> -->
</view>

js相关:
/**

  • 页面的初始数据
    */
    data: {
    filePath: ‘’,
    showPath:’’,
    status: ‘front’,
    w: app.globalData.winWidth,
    h: app.globalData.screenHeight,
    cw: 300,
    ch: 200,
    hideTakeButton: false,
    hideCoverImage: true,
    hideCoverButton: true,
    hideMask:false
    },
    压缩方法:
    //处理页面绑定事件
    takePhoto() {
    let that = this;
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
    quality: ‘high’,
    success: (res) => {
    let tempPath = res.tempImagePath
    that.setData({
    showPath : tempPath
    })
    let zipedPath = ‘’;
    //直接压缩开始
    wx.compressImage({
    src: tempPath,
    quality:60,
    success:function®{
    zipedPath= r.tempFilePath
    //console.log(“压缩后:” + zipedPath);
    that.setData({
    filePath: zipedPath,
    hideTakeButton: true,
    hideMask:true,
    hideCoverButton: false,
    hideCoverImage: false
    })
    }
    })
    //直接压缩结束
    },
    fail: function() {
    wx.showToast({
    title: ‘照片拍摄失败,请检查摄像头’,
    icon: ‘none’
    })
    }
    })
    },

//点击确定才开始上传文件
confirm: function() {
let that = this;
that.setData({
hideCoverButton: true
});
wx.showLoading({
title: ‘图片上传中…’,
mask: true
})

//调用文件处理方法
//that.zipImage();
//上传压缩过的文件
let uploadfilePath = that.data.filePath;
console.log("获取上传图片:"+uploadfilePath)
that.uploadzipBase64(uploadfilePath);

},

//重拍按钮
takeAgain: function() {
let that = this;
that.setData({
hideTakeButton: false,
hideMask:false,
hideCoverImage: true,
hideCoverButton: true,
filePath: ‘’
});
},

//图片压缩后直接上传BASE64格式
zipImage: function() {
let that = this;
let filePath = that.data.filePath;
var uploadFile = ‘’;
//文件压缩
//获得原始图片大小
wx.getImageInfo({
src: filePath,
success(res) {
var originWidth = res.width;
var originHeight = res.height;
console.log(“原始宽高比” + originWidth + “:” + originHeight);
//设置压缩比例,最大尺寸限度
var maxWidth = 1200;
var maxHeight = 600;
//目标尺寸
var targetWidth = originWidth;
var 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(filePath, 0, 0, targetWidth, targetHeight);
//canvas压缩后图片处理要写在draw方法的回调里
ctx.draw(false, function callback() {

      //更新canvas大小
      that.setData({
        cw: targetWidth,
        ch: targetHeight
      });
      //保存图片
      setTimeout(function() {
        wx.canvasToTempFilePath({
          canvasId: 'firstCanvas',
          fileType: 'jpg',
          success: (res) =&gt; {
            uploadFile = res.tempFilePath;
            //上传
            that.uploadzipBase64(uploadFile);
          }
        }, this)
      }, 500);

    });

  },
  fail() {
    wx.showToast({
      title: '获取图片失败',
      icon: 'none'
    })
  }
})

},

//转BASE64并上传
uploadzipBase64(uploadFile) {
let that = this;
//通过文件系统管理器重新编码文件
const fs = wx.getFileSystemManager();
fs.readFile({
filePath: uploadFile,
encoding: “base64”,
success: function(res) {
var base64Data = res.data;
console.log(“开始上传”)
//调用你的ajax请求上传后台
ajaxUpload();
},
fail: function() {
wx.showToast({
title: ‘读取图片失败’,
icon: ‘none’
})
}
});

},

//绑定出错事件
error(e) {
wx.showToast({
title: ‘照片拍摄失败,请检查摄像头’,
icon: ‘none’
})
}
总结:
以上示例,图片压缩可以通过2种方式:
1.官方的api:wx.compressImage({})
2.利用canvas进行压缩重绘
转化为BASE64编码方式:通过文件系统管理器,读文件转化
const fs = wx.getFileSystemManager();

回到顶部