uni-app 实现拍照后给照片加水印功能

遇到个需求需要实现,研究了一下后写了个demo

本质上就是把拍完照后的照片放到canvas里,然后加上水印样式然后再重新生成一张图片

代码如下,看注释即可~使用的话记得还是得优化下代码

javascript 复制代码
<template>
  <view class="content">
    <button @click="handlePhotoAndWatermask">测试按钮</button>
    <!-- uni-app必须要有一个canvas元素 -->
    <!-- 所以在这里放置一个并且将它隐藏起来 -->
    <view style="position: absolute; left: 9999px">
      <canvas
        canvas-id="myCanvas"
        :style="{ width: `${canvasWidth}px`, height: `${canvasHeight}px` }"
      ></canvas>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 300,
      canvasHeight: 150,
    }
  },
  methods: {
    handlePhotoAndWatermask() {
      // 调用拍照功能
      uni.chooseMedia({
        mediaType: ['image'],
        sourceType: ['camera'],
        maxDuration: 30,
        camera: 'back',
        success: (res) => {
          const filePath = res.tempFiles[0].tempFilePath

          // 获取图片宽高
          uni.getImageInfo({
            src: filePath,
            success: ({ width, height }) => {
              // 将canvas的宽高置成同样的宽高
              this.canvasWidth = width
              this.canvasHeight = height

              // 用this.$nextTick不行,第一次还是会按默认的300 * 150截取
              // setTimeout时间也不能太短,500ms左右
              setTimeout(() => {
                const ctx = uni.createCanvasContext('myCanvas')
                // 将图片放到canvas中
                ctx.drawImage(filePath, 0, 0, width, height)

                // 加上想要绘制的水印
                ctx.font = '50px system-ui'
                ctx.fillStyle = 'red'
                ctx.fillText('测试写入', 20, 100)
                ctx.draw()

                // 将canvas转化成图片
                uni.canvasToTempFilePath({
                  canvasId: 'myCanvas',
                  width: this.canvasWidth,
                  height: this.canvasHeight,
                  success: ({ tempFilePath }) => {
                    // 可以对生成的图片做你需要的操作
                    uni.previewImage({
                      current: 0,
                      urls: [tempFilePath],
                    })
                  },
                })
              }, 500)
            },
            fail() {
              console.error('获取图片详情失败')
            },
          })
        },
      })
    },
  },
}
</script>

最终展示效果如下~

PS: 这个只是小程序版,不过App端也是类似的实现方式~

相关推荐
李鸿耀9 分钟前
仅用几行 CSS,实现优雅的渐变边框效果
前端
码事漫谈29 分钟前
解决 Anki 启动器下载错误的完整指南
前端
赵庆明老师36 分钟前
Uniapp微信小程序开发:微信小程序支付功能后台代码
微信小程序·小程序·uni-app
曹申阳40 分钟前
1. 使用VSCode开发uni-app环境搭建
ide·vscode·uni-app
im_AMBER1 小时前
Web 开发 27
前端·javascript·笔记·后端·学习·web
蓝胖子的多啦A梦1 小时前
低版本Chrome导致弹框无法滚动的解决方案
前端·css·html·chrome浏览器·版本不同造成问题·弹框页面无法滚动
玩代码1 小时前
vue项目安装chromedriver超时解决办法
前端·javascript·vue.js
訾博ZiBo2 小时前
React 状态管理中的循环更新陷阱与解决方案
前端
StarPrayers.2 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
一壶浊酒..2 小时前
ajax局部更新
前端·ajax·okhttp