前端上傳圖片時(shí)添加水印

前段時(shí)間有個(gè)功能需要上傳圖片并添加水印,于是就查了些資料,但是大部分都不太適用,或者說(shuō)沒(méi)反應(yīng)。

先說(shuō)下需要用到的,canvas,添加水印,只能用這個(gè)去創(chuàng)建畫布,把文字平鋪到畫布上

用到的ui時(shí)ant-design-vue,應(yīng)該下面的方法對(duì)別的ui也是可以的

上傳文件組件有個(gè)上傳前的方法: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>

畫布這時(shí)就需要在beforeUploadHandle這個(gè)方法中去生成水印,然后通過(guò)后端上傳接口,把圖片傳給后端,然后再接收后端返回的數(shù)據(jù)
下面是beforeUploadHandle方法

beforeUploadHandle(file) {
      return new Promise((resolve) => {
        const reader = new FileReader()
        reader.readAsDataURL(file) // file轉(zhuǎn)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// 設(shè)定文字大小隨圖片大小變化
            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' // 水印對(duì)其的基準(zhǔn)線
              ctx.font = `50px Verdana` // 文字大小
              ctx.fillText('僅供展示,嚴(yán)禁盜用,復(fù)印無(wú)效', 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' // 水印對(duì)其的基準(zhǔn)線
              ctx.font = `50px Verdana` // 文字大小
              ctx.fillText('僅供展示,嚴(yán)禁盜用,復(fù)印無(wú)效', imgWidth / 2 - i * 200, imgHeight / 2 - i * 200) // 添加的文字
              ctx.restore()
            }
            data = canvas.toDataURL(file.type) // 輸出壓縮后的base64
            // base64轉(zhuǎn)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里面是對(duì)圖片水印的角度,字體大小,中心點(diǎn),以及數(shù)量上做一個(gè)調(diào)整,
效果如下:


image.png

如果只是想做出一個(gè)效果,可以看下面的代碼,我精簡(jiǎn)了一下

beforeUploadHandle(file) {
      return new Promise((resolve) => {
        const reader = new FileReader()
        reader.readAsDataURL(file) // file轉(zhuǎn)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// 設(shè)定文字大小隨圖片大小變化
            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) //旋轉(zhuǎn)角度
            ctx.fillStyle = 'rgb(0,0,0,0.4)' // 水印顏色,透明度
            ctx.textBaseline = 'center' // 水印對(duì)其的基準(zhǔn)線
            ctx.font = `50px Verdana` // 文字大小
            ctx.fillText('僅供展示,嚴(yán)禁盜用,復(fù)印無(wú)效', 100, 100) // 添加的文字
            ctx.restore()
          
            data = canvas.toDataURL(file.type) // 輸出壓縮后的base64
            // base64轉(zhuǎn)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)
          }
        }
      })
    },

如果顯示不出水印,可以適當(dāng)?shù)娜フ{(diào)整一下ctx.translate,ctx.fillText后面的數(shù)字

大概是這樣,如有問(wèn)題會(huì)隨時(shí)修改本文章

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容