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端也是类似的实现方式~

相关推荐
爱敲代码的小杨.3 分钟前
【Spring】Spring Web MVC
前端·spring·mvc
是立不是利23 分钟前
深入理解JavaScript事件委托
开发语言·前端·javascript
晴天1633 分钟前
React 版本迭代解析:从15到19 核心差异-Day40
前端·react.js·前端框架
APItesterCris1 小时前
告别人工盯品!借助 Open‑Claw 快速搭建电商商品全自动监控与数据分析系统(完整实操代码)
java·大数据·前端·数据库
啊阿狸不会拉杆1 小时前
《计算机网络-自顶向下方法》6.7 回顾:Web页面请求的历程 读书笔记
前端·计算机网络
云上工程笔记2 小时前
四柱记账法和复式记账法有什么区别?复式记账为什么更适合查错和对账
大数据·前端·人工智能
恋猫de小郭2 小时前
Dart Skills CLI 1.0 :AI 时代的 Dart 交付支持
android·前端·flutter
Hilaku2 小时前
为什么技术极强的前端,往往当不好前端 Team Leader?
前端·javascript·程序员
Knight_AL2 小时前
EasyExcel 导入模板踩坑:row.add(““)导致文本格式失效与单元格保护问题解决方案
java·前端·easyexcel
2501_916007472 小时前
使用Apple Dashboards显示和自定iOS应用性能指标与数据可视化指南
android·ios·小程序·https·uni-app·iphone·webview