前端上传图片时添加水印

前段时间有个功能需要上传图片并添加水印,于是就查了些资料,但是大部分都不太适用,或者说没反应。

先说下需要用到的,canvas,添加水印,只能用这个去创建画布,把文字平铺到画布上

用到的ui时ant-design-vue,应该下面的方法对别的ui也是可以的

上传文件组件有个上传前的方法:before-upload

<a-upload
    class="avatar-uploader"
    list-type="picture-card"
    :file-list="uploadFileList"
    :custom-request="uploadDoneHandle"
    :before-upload="beforeUploadHandle"
    :remove="removeHandle"
    v-decorator="['path', { rules: formValidateRules.path }]"
    @preview="previewHandle"
    @change="uploadChangeHandle"
>
    <div v-if="uploadFileList.length < 1">
       <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
    </div>
</a-upload>

画布这时就需要在beforeUploadHandle这个方法中去生成水印,然后通过后端上传接口,把图片传给后端,然后再接收后端返回的数据
下面是beforeUploadHandle方法

beforeUploadHandle(file) {
      return new Promise((resolve) => {
        const reader = new FileReader()
        reader.readAsDataURL(file) // file转base64
        reader.onload = (e) => {
          const canvas = document.createElement('canvas')
          const img = new Image()
          img.src = e.target.result
          img.onload = () => {
            const ctx = canvas.getContext('2d')
            let data = ''
            const imgWidth = img.width
            const imgHeight = img.height
            // const fontsize = imgWidth > imgHeight ? imgHeight / 10 : imgWidth / 10// 设定文字大小随图片大小变化
            canvas.width = imgWidth // 画布宽度
            canvas.height = imgHeight // 画布高度
            ctx.drawImage(img, 0, 0, imgWidth, imgHeight) // 绘制图片大小和先前图片一致
            for (let i = 0; i < 6; i++) {
              ctx.save()
              ctx.translate(i + 50, i + 50)
              ctx.rotate((45 * Math.PI) / 180)
              ctx.fillStyle = 'rgb(0,0,0,0.3)' // 水印颜色,透明度
              ctx.textBaseline = 'center' // 水印对其的基准线
              ctx.font = `50px Verdana` // 文字大小
              ctx.fillText('仅供展示,严禁盗用,复印无效', imgWidth / 2 - i * 200, imgHeight / 2 - i * 200) // 添加的文字
              ctx.restore()

              ctx.save()
              ctx.translate(i + 600, i + 600)
              ctx.rotate((45 * Math.PI) / 180)
              ctx.fillStyle = 'rgb(0,0,0,0.4)' // 水印颜色,透明度
              ctx.textBaseline = 'center' // 水印对其的基准线
              ctx.font = `50px Verdana` // 文字大小
              ctx.fillText('仅供展示,严禁盗用,复印无效', imgWidth / 2 - i * 200, imgHeight / 2 - i * 200) // 添加的文字
              ctx.restore()
            }
            data = canvas.toDataURL(file.type) // 输出压缩后的base64
            // base64转file
            const arr = data.split(',')
            const mime = arr[0].match(/:(.*?);/)[1]
            const bstr = atob(arr[1])
            let n = bstr.length
            const u8arr = new Uint8Array(n)
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n)
            }
            const files = new File([new Blob([u8arr], { type: mime })], file.name, { type: file.type })
            files.uid = file.uid
            resolve(files)
          }
        }
      })
      /* const { result } = fileCheckForImage(file)
            return result */
    },

上面代码中的for里面是对图片水印的角度,字体大小,中心点,以及数量上做一个调整,
效果如下:
image.png

如果只是想做出一个效果,可以看下面的代码,我精简了一下

beforeUploadHandle(file) {
      return new Promise((resolve) => {
        const reader = new FileReader()
        reader.readAsDataURL(file) // file转base64
        reader.onload = (e) => {
          const canvas = document.createElement('canvas')
          const img = new Image()
          img.src = e.target.result
          img.onload = () => {
            const ctx = canvas.getContext('2d')
            let data = ''
            const imgWidth = img.width
            const imgHeight = img.height
            // const fontsize = imgWidth > imgHeight ? imgHeight / 10 : imgWidth / 10// 设定文字大小随图片大小变化
            canvas.width = imgWidth // 画布宽度
            canvas.height = imgHeight // 画布高度
            ctx.drawImage(img, 0, 0, imgWidth, imgHeight) // 绘制图片大小和先前图片一致

            ctx.save()
            ctx.translate( 200, 200)
            ctx.rotate((45 * Math.PI) / 180) //旋转角度
            ctx.fillStyle = 'rgb(0,0,0,0.4)' // 水印颜色,透明度
            ctx.textBaseline = 'center' // 水印对其的基准线
            ctx.font = `50px Verdana` // 文字大小
            ctx.fillText('仅供展示,严禁盗用,复印无效', 100, 100) // 添加的文字
            ctx.restore()
          
            data = canvas.toDataURL(file.type) // 输出压缩后的base64
            // base64转file
            const arr = data.split(',')
            const mime = arr[0].match(/:(.*?);/)[1]
            const bstr = atob(arr[1])
            let n = bstr.length
            const u8arr = new Uint8Array(n)
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n)
            }
            const files = new File([new Blob([u8arr], { type: mime })], file.name, { type: file.type })
            files.uid = file.uid
            resolve(files)
          }
        }
      })
    },

如果显示不出水印,可以适当的去调整一下ctx.translate,ctx.fillText后面的数字

大概是这样,如有问题会随时修改本文章

posted @ 2022-11-09 17:19  与君别  阅读(472)  评论(0编辑  收藏  举报