手把手带你在小程序中实现保存图片组件功能

 4503

本篇文章带大家聊聊微信小程序保存图片组件开发,希望对大家有所帮助!


手把手带你在小程序中实现保存图片组件功能


许多微信小程序通过保存海报让用户去分享活动让更多的人知道自己的小程序,想必在平时开发小程序的时候应该有遇见过吧。


今天我就来分享下之前在公司做的一个小程序保存海报的功能。首先我先描述下之前在公司做的需求是什么样的。公司上线的小程序会有一个长期的活动目的就是去推广新用户,每个用户都要有一张属于自己的海报,通过个人海报去推广则只是单纯的一种方式。

接到任务后,我也先去万能互联网做了调查但是我的师兄和我说这个做过类似的但是当时只是单纯为了完成任务所以代码很乱,然后他就从其他项目的代码找呀找,然后找到了给我~~~ 而当时给到我的时间紧任务重呀只好先用着调整一些并且交差了。之后呢我就根据网上的文章然后一步一步踩坑,一步一步走实现了一个保存海报的组件。

思路

首先声明下组件采用的是uniapp,具体实现了可以绘制图片、绘制文字以及保存海报至相册的基本功能,在开发中这些也完全够用了。

通过canvas绘制海报。通过uni.canvasToTempFilePath 将绘制好的 canvas转为图片。通过uni.saveImageToPhotosAlbum 将本地临时路径的图片保存至手机相册中。而我的想法是将所有采用的方法全部封装到组件中,只通过父组件去调用需要使用的方法和调整相关的参数即可。 具体使用可以查看示例代码


通过canvas绘制海报内容的顺序先后问题

通过使用promise对象决定绘制海报内容的顺序先后。promise.all()方法进行canvas最后一步的绘画操作 context.draw()

注意uni.getImageInfo()

在绘制图片 和 头像时,组件通过uni.getImageInfo() 去获取图片的相关信息,调用该方法成功的前提是需要在微信小程序后台配置download域名和request域名当然最好把uploadFile域名也一起配置,防止出差错。但是官方给出的提示是配置download域名白名单即可,但是获取不到图片信息,这算是一个大坑了。

如果没有进行相关配置,在调试时 或者 体验版 正式版等 打开了vconsole调试工具。uni.getImageInfo() 是可以获取到图片信息的,一旦关闭了vconsole uni.getImageInfo() 将会fail, 也是个坑。

本组件方法,变量介绍

props

canvasInfo Object (必需)

canvasWidth 画布宽度

canvasHeight 画布高度

canvasId 画布标识

isFullScreen Boolean

为ture时表示画布为手机屏幕全屏,canvasInfo设置的宽高将失效。

默认为 false

methods

canvasInit(callback) canvas初始化,所有有关画布canvas操作需在其回调函数操作。

drawCanvasImage(context, src, _imageWidth, _imageHeight, dx, dy) 在canvas绘制一张图片

drawCircularAvatar(context, url, _circularX, _circularY, _circularR) 在canvas绘制一张圆形图片

drawText(options) 在canvas绘制单行、多行文本

startDrawToImage(context, promiseArr, callback) 将canvas操作draw()进行绘制

posterToPhotosAlbum(filePath) 保存至手机相册


示例代码

  1. <template>
  2.     <view>
  3.         <view class="savePosterItem">
  4.             <image v-show="tempFilePath" :src="tempFilePath"></image>
  5.             <save-poster-com v-show="!tempFilePath" ref="savePoster" :canvasInfo="canvasInfo"></save-poster-com>
  6.         </view>
  7.          
  8.          
  9.         <button class="savePosterBtn" type="primary" @click="saveBtnFun">保存海报</button>
  10.     </view>
  11. </template>
  12.  
  13. <script>
  14.     import SavePosterCom from '@/components/SavePosterCom/SavePosterCom.vue'
  15.     export default {
  16.         components: {
  17.             SavePosterCom
  18.         },
  19.         data() {
  20.             return {
  21.                 canvasInfo: {
  22.                     canvasWidth: 620,
  23.                     canvasHeight: 950,
  24.                     canvasId: 'save-poster'
  25.                 },
  26.                 tempFilePath: '',
  27.                 canvasBgUrl: 'https://images.pexels.com/photos/4065617/pexels-photo-4065617.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500',
  28.                 avatarUrl: 'https://p9-passport.byteacctimg.com/img/user-avatar/4dbf31fa6dec9c65b78a70d28d843c04~300x300.image'
  29.             }
  30.         },
  31.         onLoad() {
  32.             let {
  33.                 drawCanvasImage,
  34.                 drawCircularAvatar,
  35.                 drawText
  36.             } = this.$refs.savePoster.$options.methods
  37.             this.$refs.savePoster.canvasInit(({
  38.                 context,
  39.                 comThis
  40.             }) => {
  41.                 // 获取画布宽高
  42.                 let canvasWH = comThis.canvasWH
  43.                 // 绘制海报背景图
  44.                 let promise_1 = drawCanvasImage(context, this.canvasBgUrl, canvasWH.canvasWidth, canvasWH.canvasHeight)
  45.                 // 必须先绘制玩海报背景图 再去操作其他绘制内容
  46.                 promise_1.then(res => {
  47.                     let promise_2 = drawCircularAvatar(context, this.avatarUrl, canvasWH.canvasWidth / 2, canvasWH.canvasHeight /
  48.                         7, 70)
  49.                      
  50.                     let promise_3 = drawText({
  51.                         context: context,
  52.                         text: '皮皮虾仁',
  53.                         dx: (canvasWH.canvasWidth / 2) + 60,
  54.                         dy: canvasWH.canvasHeight / 4,
  55.                         fontSize: 30,
  56.                         fontColor: '#5D4037'
  57.                     })
  58.                      
  59.                     let promise_4 = drawCanvasImage(context, this.avatarUrl, 150, 150, (canvasWH.canvasWidth / 2) + 85, (canvasWH.canvasHeight -
  60.                         165))
  61.                       
  62.                     this.$refs.savePoster.startDrawToImage(context, [promise_1,promise_2,promise_4], (tempFilePath) => {
  63.                         this.tempFilePath = tempFilePath
  64.                     })
  65.                 })
  66.             })
  67.         },
  68.         methods: {
  69.             saveBtnFun() {
  70.                 uni.showModal({
  71.                     title: '保存海报',
  72.                     content: '海报将被保存至相册中',
  73.                     confirmText: '保存',
  74.                     success: (res) => {
  75.                         if(res.confirm) {
  76.                             this.$refs.savePoster.posterToPhotosAlbum(this.tempFilePath)
  77.                         }
  78.                     }
  79.                 })
  80.             }
  81.         }
  82.     }
  83. </script>
  84.  
  85. <style>
  86.     .savePosterItem {
  87.         text-align: center;
  88.     }
  89.     .savePosterItem > image {
  90.         width: 620rpx;
  91.         height: 950rpx;
  92.     }
  93.      
  94.     .savePosterBtn {
  95.         margin-top: 40rpx;
  96.         width: 80%;
  97.     }
  98. </style>


组件源码

  1. <template>
  2.     <view>
  3.         <canvas :canvas-id="canvasInfo.canvasId" :style="{width: canvasWH.canvasWidth + 'px', height: canvasWH.canvasHeight + 'px'}"></canvas>
  4.     </view>
  5. </template>
  6.  
  7. <script>
  8.     export default {
  9.         name: 'savePosterCom',
  10.         data() {
  11.             return {
  12.                 userPhoneWHInfo: {},
  13.                 canvasWH: {
  14.                     canvasWidth: 0,
  15.                     canvasHeight: 0
  16.                 }
  17.             }
  18.         },
  19.         props: {
  20.             // 决定保存下来的图片的宽高
  21.             canvasInfo: {
  22.                 type: Object,
  23.                 default: () => {
  24.                     return {
  25.                         canvasWidth: 0,
  26.                         canvasHeight: 0,
  27.                         canvasId: 'canvasId'
  28.                     }
  29.                 }
  30.             },
  31.             // canvas画布是不是全屏,默认是false。 false时使用必须传 canvasInfo
  32.             isFullScreen: Boolean
  33.         },
  34.         created() {
  35.             this.userPhoneWHInfo = this.getPhoneSystemInfo()
  36.             if (this.isFullScreen) { // 画布全屏
  37.                 this.canvasWH.canvasWidth = this.userPhoneWHInfo.windowWidth
  38.                 this.canvasWH.canvasHeight = this.userPhoneWHInfo.windowHeight
  39.             } else { // 指定宽高
  40.                 this.canvasWH.canvasWidth = this.canvasInfo.canvasWidth
  41.                 this.canvasWH.canvasHeight = this.canvasInfo.canvasHeight
  42.             }
  43.         },
  44.         mounted() {},
  45.         methods: {
  46.             /**
  47.             * 获取用户手机屏幕信息
  48.             */
  49.             getPhoneSystemInfo() {
  50.                 const res = uni.getSystemInfoSync();
  51.                 return {
  52.                     windowWidth: res.windowWidth,
  53.                     windowHeight: res.windowHeight
  54.                 }
  55.             },
  56.             /** 获取 CanvasContext实例
  57.             * @param {String} canvasId 
  58.             */
  59.             getCanvasContextInit(canvasId) {
  60.                 return uni.createCanvasContext(canvasId, this)
  61.             },
  62.             /** 保存海报组件初始化
  63.             * @param {Function} callback(context) 回调函数
  64.             */
  65.             canvasInit(callback) {
  66.                 let context = this.getCanvasContextInit(this.canvasInfo.canvasId)
  67.                 if (context) {
  68.                     callback({
  69.                         context: context,
  70.                         comThis: this
  71.                     })
  72.                 }
  73.             },
  74.             /** 将上诉的绘制画到画布中 并且 将画布导出为图片
  75.             *  @param context 画布
  76.             *  @param {Promise[]} 存放Promise的数组 
  77.             *  @param {Function} callback 保存图片后执行的回调函数(本地图片临时路径)
  78.             */
  79.             startDrawToImage(context, promiseArr, callback) {
  80.                 // 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中
  81.                 let canvasId = this.canvasInfo.canvasId
  82.                 let tempFilePath = ''
  83.                 Promise.all(promiseArr).then(res => {
  84.                     context.draw(false, async () => {
  85.                         callback(await this.canvasToImage(canvasId))
  86.                     })
  87.                 })
  88.             },
  89.             /**
  90.             * 在canvas绘制一张图片
  91.             * @param context 画布
  92.             * @param src 图片资源
  93.             * @param _imageWidth 图片宽度
  94.             * @param _imageHeight 图片高度 
  95.             */
  96.             drawCanvasImage(context, src, _imageWidth, _imageHeight, dx, dy) {
  97.                 return new Promise((resolve, reject) => {
  98.                     uni.getImageInfo({
  99.                         src: src,
  100.                         success: res => {
  101.                             context.drawImage(res.path, (dx - _imageWidth), (dy - _imageHeight), _imageWidth, _imageHeight)
  102.                             resolve(context)
  103.                         },
  104.                     })
  105.                 })
  106.             },
  107.             /** 绘制一个圆形头像
  108.             * @param  context 画布 
  109.             * @param  url     图片地址
  110.             * @param  _circularX  圆心X坐标
  111.             * @param  _circularY  圆心Y坐标
  112.             * @param  _circularR  圆半径
  113.             */
  114.             drawCircularAvatar(context, url, _circularX, _circularY, _circularR) {
  115.                 let dx = _circularX - _circularR;
  116.                 let dy = _circularY - _circularR;
  117.                 let dwidth = _circularR * 2;
  118.                 let dheight = _circularR * 2
  119.                 return new Promise((resolve, reject) => {
  120.                     uni.downloadFile({
  121.                         url: url,
  122.                         success: res => {
  123.                             context.save()
  124.                             context.beginPath()
  125.                             // _circularX圆的x坐标  _circularY圆的y坐标  _circularR圆的半径
  126.                             context.arc(_circularX, _circularY, _circularR, 0, 2 * Math.PI)
  127.                             context.clip()
  128.                             // dx: 图像的左上角在目标canvas上 X 轴的位置
  129.                             // dy: 图像的左上角在目标canvas上 Y 轴的位置
  130.                             // dwidth: 在目标画布上绘制图像的宽度,允许对绘制的图像进行缩放
  131.                             // dheight: 在目标画布上绘制图像的高度,允许对绘制的图像进行缩放
  132.                             context.drawImage(res.tempFilePath, dx, dy, dwidth, dheight)
  133.                             context.restore()
  134.                             // context.draw()
  135.                             resolve(context)
  136.                         }
  137.                     })
  138.                 })
  139.             },
  140.             /** 绘制多行文本 注:, 和 空格都算一个字
  141.             * @param context 画布
  142.             * @param text 需要被绘制的文本
  143.             * @param dx 左上角x坐标
  144.             * @param dy 右上角y坐标
  145.             * @param rowStrnum 每行多少个字 (默认为text字体个数->单行)
  146.             * @param fontSize 文字大小 (默认16)
  147.             * @param fontColor 文字颜色 (默认black)
  148.             * @param lineHeight 单行文本行高 (默认0)
  149.             */
  150.             drawText(options) {
  151.                 let {
  152.                     context,
  153.                     text,
  154.                     dx,
  155.                     dy,
  156.                     rowStrnum = text.length,
  157.                     lineHeight = 0,
  158.                     fontSize = 16,
  159.                     fontColor = 'black'
  160.                 } = options
  161.                 return new Promise((resolve, reject) => {
  162.                     context.setFontSize(fontSize)
  163.                     context.setFillStyle(fontColor)
  164.                     context.setTextBaseline('middle')
  165.                     // 获取需要绘制的文本宽度
  166.                     let textWidth = Number(context.measureText(text).width)
  167.                     // console.log('textWidth',textWidth)
  168.                     // 获取文本的字数 
  169.                     let textNum = text.length
  170.                     // 获取行数 向上取整
  171.                     let lineNum = Math.ceil(textNum / rowStrnum)
  172.                     // console.log('textNum',textNum)
  173.                     // console.log('lineNum',lineNum)
  174.                     for (let i = 0; i < lineNum; i++) {
  175.                         let sliceText = text.slice(* rowStrnum, (+ 1) * rowStrnum)
  176.                         // fillText 的 dx = 文字最左边的距离到屏幕政策的距离
  177.                         context.fillText(sliceText, dx - textWidth, dy + i * lineHeight);
  178.                     }
  179.                     resolve(context)
  180.                 })
  181.             },
  182.             /** 将画布导出为图片
  183.             * @param canvasId 画布标识
  184.             */
  185.             canvasToImage(canvasId) {
  186.                 return new Promise((resolve, reject) => {
  187.                     uni.canvasToTempFilePath({
  188.                         canvasId: canvasId, // 画布标识
  189.                         success: res => {
  190.                             // 在H5平台下,tempFilePath 为 base64
  191.                             resolve(res.tempFilePath)
  192.                         },
  193.                         fail: err => {
  194.                             console.log('err', err)
  195.                             reject(err)
  196.                         }
  197.                     }, this)
  198.                 })
  199.             },
  200.             /** 保存生成的图片到本地相册中
  201.             *  @param {String} filePath 图片临时路劲
  202.             */
  203.             posterToPhotosAlbum(filePath) {
  204.                 console.log('filePath',filePath)
  205.                 uni.showLoading({
  206.                     title: '保存中...'
  207.                 })
  208.                 uni.saveImageToPhotosAlbum({
  209.                     filePath: filePath,
  210.                     success: (res) => {
  211.                         uni.showToast({
  212.                             title: '保存成功,请前往手机相册中查看',
  213.                             mask: true,
  214.                             icon: 'none',
  215.                             duration: 2000
  216.                         })
  217.                     },
  218.                     fail: (err) => {
  219.                         console.log('err',err)
  220.                         if (err.errMsg.includes('deny')||err.errMsg.includes('denied')) { // 用户选择拒绝 
  221.                             this.openSetting()
  222.                         } else if (err.errMsg.includes('fail cancel')) { // 用户在保存图片时 取消了
  223.                             uni.showToast({
  224.                                 title: '已取消保存,无法保存至相册',
  225.                                 mask: true,
  226.                                 icon: 'none',
  227.                                 duration: 2000
  228.                             })
  229.                             return
  230.                         }
  231.                     },
  232.                     complete: () => {
  233.                         uni.hideLoading()
  234.                     }
  235.                 })
  236.             },
  237.             /**
  238.             * 打开摄像头设置权限页面
  239.             */
  240.             openSetting() {
  241.                 uni.showModal({
  242.                     title: '温馨提示',
  243.                     content: '保存图片至相册中,需要您同意添加访问相册权限',
  244.                     cancelText: '拒绝',
  245.                     confirmText: '同意',
  246.                     success: res => {
  247.                         if (res.confirm) {
  248.                             uni.openSetting({
  249.                                 success: settingdata => {
  250.                                     if (settingdata.authSetting['scope.writePhotosAlbum']) {
  251.                                         console.log('获取权限成功,给出再次点击图片保存到相册的提示。')
  252.                                         uni.showToast({
  253.                                             title: '授权成功,请再次点击保存',
  254.                                             icon: 'none',
  255.                                             duration: 2000,
  256.                                         })
  257.                                     } else {
  258.                                         console.log('获取权限失败,给出不给权限就无法正常使用的提示')
  259.                                         uni.showToast({
  260.                                             title: '需要访问相册权限',
  261.                                             icon: 'none',
  262.                                             duration: 2000,
  263.                                         })
  264.                                     }
  265.                                 },
  266.                                 fail: (res) => {
  267.                                     console.log('err', err)
  268.                                 }
  269.                             })
  270.                         } else {
  271.                             uni.showToast({
  272.                                 title: '已拒绝授权,无法保存至相册',
  273.                                 mask: true,
  274.                                 icon: 'none',
  275.                                 duration: 2000
  276.                             })
  277.                             return
  278.                         }
  279.                     }
  280.                 })
  281.             }
  282.         }
  283.     }
  284. </script>
  285.  
  286. <style>
  287. </style>


效果


手把手带你在小程序中实现保存图片组件功能

本文网址:https://www.zztuku.com/index.php/detail-9747.html
站长图库 - 手把手带你在小程序中实现保存图片组件功能
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐