前端图片转base64方法及下载图片方法

前端图片转base64方法

getImageFromUrl(url) {
    return axios({
      url,
      method: 'get',
      responseType: 'blob' // 指定响应数据的类型为 blob(二进制数据)
    }).then(response => {
        const fileReader = new FileReader();
        fileReader.readAsDataURL(response.data);
        return new Promise(resolve => {
           fileReader.onload = () => {
               const base64Data = fileReader.result;
               resolve(base64Data);
           };
        });
    });
}

下载图片:

export const download = (url) => {
  let img = new Image();
  img.src = url;
  img.crossOrigin = 'anonymous';
  img.onload = function() {
    let canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    let ctx = canvas.getContext('2d');
    ctx.drawImage(img,0,0);
    canvas.toBlob(function(blob) {
      FileSaver.saveAs(blob, 'test.jpg');
    });
  }
}

你可能感兴趣的:(前端)