图片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 = "*"
原文地址:https://www.cnblogs.com/zhaobao1830/p/11579172.html