TypeScript - 获取网络图片格式

三味码屋 2024年06月16日 56次浏览

在 TypeScript 中,要获取网络图片的格式,可以发送 HTTP 请求来获取图片资源的内容,然后根据内容的 MIME 类型来判断格式。以下是一个使用 axios 库和 file-type 库来判断网络图片格式的示例代码:
首先,需要安装 axios 和 file-type:

npm install axios file-type

然后,使用以下 TypeScript 代码来获取网络图片的格式:

import axios from 'axios';
import { FileTypeResult } from 'file-type';
 
async function getImageFormat(imageUrl: string): Promise<FileTypeResult | undefined> {
  try {
    // 发送 HEAD 请求,避免下载整个图片
    const response = await axios.head(imageUrl);
    if (response.headers['content-type']) {
      // 使用 file-type 库解析 MIME 类型
      return fileType.fromMime(response.headers['content-type'] as string);
    }
  } catch (error) {
    console.error('Error fetching image or parsing content type:', error);
  }
  return undefined;
}
 
// 使用函数
getImageFormat('https://example.com/image.jpg').then(result => {
  if (result) {
    console.log(`Image format is: ${result.ext}`);
  } else {
    console.log('Unable to determine image format');
  }
});

这段代码首先发送一个 HTTP HEAD 请求到图片的 URL 以获取内容类型,然后使用 file-type 库来解析这个内容类型,从而得到图片格式。如果请求成功,它会返回一个 FileTypeResult 对象,其中包含了扩展名属性 ext,表示图片格式。如果发生错误或者无法解析内容类型,则返回 undefined。