基于uni-app的小程序端的上传图片并进行图片压缩
2022/2/11 22:13:04
本文主要是介绍基于uni-app的小程序端的上传图片并进行图片压缩,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
<image :src="img" @tap.stop="clickImg"></image> // 第四步:在canvas绘制图片需要,不能隐藏!!! <canvas canvas-id="firstCanvas" id="firstCanvas" :style="'width:' + canvasWidth +'px;height:' + canvasHeight + 'px;position:absolute;left:-10000px;top:-10000px'"></canvas>
clickImg() { // 1. 选择图片 uni.chooseImage({ count: 1, //一次最多选择数量 sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album'], // 从相册选择 success: function (res) { if(res.tempFiles[0].size >= 10485760) { // 提示:文件大于10M,请重新选择! return; } // 2. 获取图片宽高 uni.getImageInfo({ src: res.tempFilePaths[0], success (ress) { // 3. 获取设备像素比,不获取最后图片展示有问题 wx.getSystemInfo({ success: function(info) { // 4. 在canvas绘制图片 const ctx = uni.createCanvasContext("firstCanvas", that); that.canvasWidth = ress.width/info.pixelRatio; that.canvasHeight = ress.height/info.pixelRatio; ctx.drawImage(ress.path, 0, 0, that.canvasWidth, that.canvasHeight); ctx.draw(false, setTimeout(function() { // 5. 压缩图片,不支持type=2d!!! uni.canvasToTempFilePath({ x: 0, y: 0, width: that.canvasWidth, height: that.canvasHeight, destWidth: that.canvasWidth, destHeight: that.canvasHeight, canvasId: "firstCanvas", quality: .5, success: function(data) { // 6. 将压缩的图片转变为二进制流 wx.getFileSystemManager().readFile({ filePath: data.tempFilePath, encoding: "base64", success: datas => { // 将二进制流文件复制给image,进行展示 that.img = "data:image/jpeg;base64," + datas.data; }, fail: (e) => { // 提示: 图片压缩失败 }, }) }, fail: (e) => { // 提示:图片信息获取失败 } }, that); }, 1000)); } }) }, fail: (e) => { // 提示:图片信息获取失败 } }) }, fail: (e) => { if(e.errMsg !== "chooseImage:fail cancel") { // 提示:上传失败 } }, }); },
这篇关于基于uni-app的小程序端的上传图片并进行图片压缩的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-30微信小程序的网络设置,及网络请求:wx.request(OBJECT)
- 2024-01-22基于taro搭建小程序多项目框架
- 2024-01-13小程序开发:在插件市场寻找步骤条组件并二开
- 2024-01-05钉钉小程序生态—企业机器人加互动卡片,改善用户体验的开始!
- 2023-12-29【UniApp】-uni-app-打包成小程序
- 2023-12-26性能翻倍!京东亿级体量小程序优化实践
- 2023-12-25小程序优化:第三方SDK过大解决方案
- 2023-11-26微信小程序文件预览和下载-文件系统
- 2023-11-2652天学习微信小程序计划No.2:注册小程序账号&安装开发者工具
- 2023-11-1952天学习微信小程序计划No.1:小程序简介