圖片url轉換成base64,base64轉file以及圖片緩存跨域的處理


let bgcImage = 'http://192.168.0.83:9080/files/4a9c3056-9b9b-4b41-b8e2-fd9f27023c41.jpg'
let image = new Image()
    image.crossOrigin = '' // 必須有這個
    image.src = bgcImage + '?v=' + Math.random()
    image.onload = () => { // 圖片加載完成后,調用getBase64Image方法 
        let base64ImageSrc = getBase64Image(image)
        console.log(base64ImageSrc )
}

// url轉base64
export function getBase64Image(image, width, height) { // width、height調用時傳入具體像素值,控制大小 ,不傳則默認圖像大小
  let canvas = document.createElement('canvas')
  canvas.width = width !== undefined ? width : image.width
  canvas.height = height !== undefined ? height : image.height
  let ctx = canvas.getContext('2d')
  ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
  let ext = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase()
  let dataURL = canvas.toDataURL('image/' + ext)
  return dataURL
}

 

// base64轉file
export function dataURLtoFile (dataurl, filename) {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}

 

備注:

雖然設置了image.crossOrigin來解決跨域問題,但有時候還是會出現跨域錯誤,這是因為圖片url的緩存

https://stackoverflow.com/questions/46609800/canvas-crossorigin-anonymous-cors-chrile-mac-osx

If your images come from a different domain, and you want to be able to export the canvas content after you did draw these images, then you have no choice than loading them with the crossOrigin attribute.

If you are really facing the linked bug, according to it, the proper fix is to always send the CORS headers from your server response, whether or not the request is made with the Origin header.

And a fast workaround is to avoid the cache, by appending a random query string in the image's src (img.src = url + '?v=' + Math.random();).

需要加個隨機數防止緩存即可

let image = new Image()
image.src = this.networkImg + '?v=' + Math.random()
image.crossOrigin = "*"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM