react utif tif格式图片预览

1、npm install @types/utif --save-dev

2、import { decode, decodeImage,toRGBA8} from 'utif';

3、

export const GetFile = (url: string, id: string, type?: number) => {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    url += '?id=' + id + '';
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = (e) => {
      if (xhr.status === 200) {
        try {
          let imgInfo = decode(xhr.response)[0];
          decodeImage(xhr.response,imgInfo);
          let imgToRGBA8 = toRGBA8(imgInfo);
          var canvas = document.createElement('canvas');
          var context = canvas.getContext('2d');
          canvas.width = imgInfo.width;
          canvas.height =imgInfo.height;
          var imageData = context.createImageData(imgInfo.width, imgInfo.height);
          imageData.data.set(imgToRGBA8);
          context.putImageData(imageData, 0, 0);
          let result=canvas.toDataURL("image/png");
          resolve(result);

        } catch (error) {
          reject(new Error(error));
        }
      } else {
        reject(new Error('图片获取失败'));
      }
    };
    xhr.send();
  }).catch((e) => {
    return e;
  });
};

  

posted @ 2022-04-07 14:26  燕林  阅读(313)  评论(0编辑  收藏  举报