0

I'm trying to get the content-type of an image from an image object. I know that it is possible to fetch it with a HEAD request:

fetch(img.src, { method: 'HEAD' })
    .then(response => response.headers.get('Content-type'))

This approach however does not really make use of browser caching / priorities of assets etc.

Instead, I would like to use the native images object:

const img = new Image();
img.src = url;

img.onload = ev => {
   // figure out mime type here?
 };

But I'm not sure how to get the image type here?

Xen_mar
  • 8,330
  • 11
  • 51
  • 74
  • You generally don't: you load the image as byte data, and then read those bytes to find specific [signatures or magic numbers](https://en.wikipedia.org/wiki/List_of_file_signatures) that tell you what kind of image you're dealing with. Of course, "you" shouldn't, that's just what ultimately needs to happen, you'd just find a library that knows how to detect image type from the actual file data and then use that so you don't have to write a byte parser yourself. – Mike 'Pomax' Kamermans Aug 30 '22 at 15:19
  • Does this answer your question? [How to get mimeType from HTMLImageElement?](https://stackoverflow.com/questions/72796785/how-to-get-mimetype-from-htmlimageelement) – Peter Seliger Aug 30 '22 at 15:20

0 Answers0