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

相关推荐
_丿丨丨_4 小时前
XSS(跨站脚本攻击)
前端·网络·xss
天天进步20154 小时前
前端安全指南:防御XSS与CSRF攻击
前端·安全·xss
拾光拾趣录7 小时前
括号生成算法
前端·算法
拾光拾趣录8 小时前
requestIdleCallback:让你的网页如丝般顺滑
前端·性能优化
前端 贾公子8 小时前
vue-cli 模式下安装 uni-ui
前端·javascript·windows
拾光拾趣录8 小时前
链表合并:双指针与递归
前端·javascript·算法
@大迁世界8 小时前
前端:优秀架构的坟墓
前端·架构
期待のcode8 小时前
图片上传实现
java·前端·javascript·数据库·servlet·交互
浩星8 小时前
uniapp运行鸿蒙报错整理
uni-app
hbrown9 小时前
Flask+LayUI开发手记(十一):选项集合的数据库扩展类
前端·数据库·python·layui