浏览器展示Heic格式的图片

3,166 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情

背景

后端返回了heic格式的图片,发现无法在浏览器展示。

解决方法

通过 heic2any 将图片转换为 jpg 来展示。

heic2any 的使用方法:

heic2any({ blob: x, toType: 'image/jpg' });

当查看 heic2any 的类型定义:

declare function heic2any({ blob, toType, quality, gifInterval, multiple, }: {
    blob: Blob;
    multiple?: true;
    toType?: string;
    quality?: number;
    gifInterval?: number;
}): Promise<Blob | Blob[]>;

发现它是接收图片的blob,然后转换为一个blob对象, 所以我们需要解决这样几个问题:

  1. 将图片URL转换为blob对象
  2. 将转换后的blob转换成 img 支持的格式。

图片URL转换为blob对象

fetch(url)
      .then(function (x) {
        return x.blob();
      })

注意: https的网站访问http的资源会报错

将转换后的blob转换成 img 支持的格式

使用window.URL.createObjectURL 将blob转换为DataURL, 然后将这个url设置给img标签的src属性即可。

const url = URL.createObjectURL(blob);

完整代码

import heic2any from 'heic2any';

export function loadHEIC(url) {
  return new Promise((resolve, reject) => {
    fetch(url, { mode: 'cors' })
      .then(function (x) {
        // console.log(x);
        return x.blob();
      })
      .then(function (x) {
        // console.log('working on', x);
        return heic2any({ blob: x, toType: 'image/jpg' });
      })
      .then(function (x) {
        const _url = URL.createObjectURL(x);
        resolve(_url);
      })
      .catch(function (e) {
        reject(e);
      });
  });
}