由于wx.compressImage(Object object) iOS 仅支持压缩 JPG 格式图片。所以我们需要做一下特别的处理:
1.获取文件,判断文件是否大于设定的大小
2.假如大于则利用canvas进行绘制,并生成新的图片路径
3.上传图片
- async chooseImage() {
- let res = await wx.chooseMedia({
- count: 1,
- sizeType: ["compressed"],
- mediaType: ['image']
- })
- if (res.tempFiles[0].size > 500 * 1024) { //大于500k
- //压缩图片
- compressImage(res.tempFiles[0], '#canvasId').then(result => {
- this.uploadFile(result.tempFilePath)
- })
- } else {
- this.uploadFile(res.tempFiles[0].tempFilePath)
- }
- },
复制代码- const compressImage = function (file, node) {
- return new Promise((resolve, reject) => {
- //获取图片的信息
- wx.getImageInfo({
- src: file.tempFilePath,
- success: async function (imageInfo) {
- //获取canvas
- const query = wx.createSelectorQuery()
- let canvasDom = query.select(node) //画布id
- canvasDom.fields({
- node: true,
- size: true
- })
- .exec((res) => {
- const canvas = res[0].node
- canvas.width = 900
- canvas.height = 900
- const ctx = canvas.getContext('2d')
- let img = canvas.createImage();
- img.src = imageInfo.path; //要压缩的图片路径
- img.onload = () => {
- // 将图片绘制到canvas
- ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
- // 生成图片
- wx.canvasToTempFilePath({
- canvas,
- destWidth: 900, //压缩后宽
- destHeight: 900, //压缩后高
- fileType: 'jpg',
- quality: 0.8, //质量,可自定义
- success: (imgResult) => {
- let fs = wx.getFileSystemManager()
- fs.getFileInfo({
- filePath: imgResult.tempFilePath,
- success: (res) => {
- //压缩后的图片如果还是大于500k,那么继续压缩直到小于500为止
- if (res.size > 500 * 1024) {
- compressImage(imgResult)
- } else {
- resolve(imgResult)
- }
- }
- })
- },
- fail: (err) => {
- console.error(err);
- reject(err)
- }
- })
- }
- })
- },
- fail: function (err) {
- console.error('获取图片信息失败:', err);
- }
- });
- })
- }
复制代码- uploadFile(avatarUrl) {
- if (avatarUrl) {
- wx.uploadFile({
- filePath: avatarUrl,
- name: 'file',
- url: "http://139.224.49.138:888/mini/myPage/uploadAvatar",
- formData: {
- openid: getApp().globalData.openid
- },
- success: (res) => {
- let {
- userInfo
- } = app.store.getState();
- userInfo.headPic = JSON.parse(res.data).url
- app.store.setState({
- userInfo: userInfo
- });
- },
- fail: err => {
- console.log(err);
- }
- })
- }
- },
复制代码- <canvas hidden="{
-
- {true}}" type="2d" id="canvasId"/>
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |