图片链接、base64、blob流,file流之间的转换,最后进行下载

1、链接 转 base64

const linkToBase64 = function(link) {
    
    
	const convertimg2base64 = (img) => {
    
    
	  const canvasEl = document.createElement('canvas')
	  canvasEl.width = img.width
	  canvasEl.height = img.height
	  const ctx = canvasEl.getContext('2d')
	  ctx.drawImage(img, 0, 0, img.width, img.height)
	  const imgsuffix = img.src.match(/\.[^\\.]+$/)[0].substring(1).toLowerCase()
	  return canvasEl.toDataURL(`image/${
      
      imgsuffix}`)
	}
	const img = new Image()
	img.src = link
	img.crossOrigin = 'anonymous' // 解决跨域问题
	img.addEventListener('load', () => {
    
    
	  const base64 = convertimg2base64(img)
	  const newimg = new Image()
	  newimg.src = base64
	  document.body.appendChild(newimg)
	})
}



2、base64 转 blob流

这里的blob流其实就是file流

const base64ToBlob = function(base64Data) {
    
    
  let arr = base64Data.split(","),
    fileType = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    l = bstr.length,
    u8Arr = new Uint8Array(l);

  while (l--) {
    
    
    u8Arr[l] = bstr.charCodeAt(l);
  }
  return new Blob([u8Arr], {
    
    
    type: fileType
  });
};



3、blob流 转 file流

将上面生成的blob流通过newBlob传入
这里其实没啥意义,就是让blob看起来更像file

const blobToFile = function(newBlob, fileName) {
    
    
  newBlob.lastModifiedDate = new Date();
  newBlob.name = fileName;
  return newBlob;
};



4、文件流 转 临时文件路径

const fileToTemporaryLink = (file) => {
    
    
	const windowURL = window.URL || window.webkitURL;
	const src = windowURL.createObjectURL(file);
	return src;
	// windowURL.revokeObjectURL(src);
}

该url对象会一直存在在document对象中,只有当document卸载时(关闭窗口)才会释放这个内存。
所以,最好在你不需要的时候,主动释放。释放方式如下:

windowURL.revokeObjectURL(src)



5、文件流 转 base64

const fileToBase64 = (file, callback) => {
    
    
	const reader = new FileReader();
	reader.readAsDataURL(file);
	reader.onload = () => {
    
    
	  const src = reader.result;
	  // 这里的reader.result就是文件的base64了。如果是图片的话,就可以直接放到src中展示了
	  callback(src);
	};
}



6、显示图片

显示图片的话使用
链接、base64、临时路径放到img标签进行显示,
blob、file放在img标签无法显示。


7、下载图片

转成base64、临时文件路径进行下载,转成blob或file流无法进行下载。
由于链接的来源类型不同不一定下载得下来,可能是直接访问。
所以最好转成base64、临时文件路径再进行下载。

const donwloadImage = (data) => {
    
    
	const newA = document.createElement("a");
	newA.href = data;
	newA.download = "风景图.png"; // 下载下来的文件名称
	newA.click();
}

猜你喜欢

转载自blog.csdn.net/qq_41231694/article/details/124930572