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

相关推荐
GIS之路20 小时前
GDAL 读取遥感影像数据
前端
fakaifa20 小时前
【独立版】智创云享知识付费小程序 v5.0.23+小程序 搭建教程
小程序·uni-app·知识付费·源码下载·智创云享独立版
IT_陈寒21 小时前
Spring Boot 3.2 新特性全解析:这5个性能优化点让你的应用提速50%!
前端·人工智能·后端
2501_9160074721 小时前
Transporter App 使用全流程详解:iOS 应用 ipa 上传工具、 uni-app 应用发布指南
android·ios·小程序·https·uni-app·iphone·webview
携欢21 小时前
PortSwigger靶场之Stored DOM XSS通关秘籍
前端·xss
LDM>W<21 小时前
Electron下载失败
前端·javascript·electron
EndingCoder21 小时前
Electron 新特性:2025 版本更新解读
前端·javascript·缓存·electron·前端框架·node.js·桌面端
BillKu21 小时前
Vue3 中使用 DOMPurify 对渲染动态 HTML 进行安全净化处理
前端·安全·html
fakaifa1 天前
CRMEB多门店 v3.3源码 无授权限制+PC端+uniapp前端
小程序·uni-app·商城小程序·技术教程·源码下载·crmeb多门店
子兮曰1 天前
🔥深度解析:Nginx目录浏览美化与功能增强实战指南
前端·javascript·nginx