Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlImageElement - how to get image type if its src doesn't have extension

Is it possible to get image type (gif, png, jpeg, etc.) with src like this?

<img src="http://d1aviatl7dpuhg.cloudfront.net/image/url/64/aHR0cDovL3BpeGNtc2FkbWluLnBpeGFibGUuY29tL3dwLWNvbnRlbnQvdXBsb2Fkcy8yMDE1LzA3L3NoYXJrLmpwZw==">

or created by new Image() constructor.

Haven't found anything helpful in W3 specs.

I guess that a separate "XHR get src" is sort of a solution, but maybe there is a better way?

Update: all sorts of XRHs are failing because of CORS, so ajax won't work here.

like image 251
sbedulin Avatar asked Jul 09 '15 09:07

sbedulin


People also ask

Why IMG src is not working?

Img src Not Working That means, when a web page loads, the browser has to retrieve the image from a web server and display it on the page. The broken link icon means that the browser could not find the image. If you've just added the image, then check that you included the correct image URL in the source attribute.

How can I get image value from src?

call(document. getElementsByTagName('img'), function(img) { return img. src; });

Does an IMG tag need a src?

The <img> tag creates a holding space for the referenced image. The <img> tag has two required attributes: src - Specifies the path to the image. alt - Specifies an alternate text for the image, if the image for some reason cannot be displayed.


2 Answers

The following works when run in an extension (which doesn't have CORS restrictions)

I've been exploring this same question, what works is the following:

  1. Download the image from the given image src as a blob
  2. The blob will have the image type in the property blob.type

Code sample (with async/await and fetch API):

async function getImageBlob(imageUrl) {
    const response = await fetch(imageUrl)
    return response.blob()
}

const blob = await getImageBlob("http://path.to.image.com")
blob.type // Image Content-Type (e.g. "image/png")
like image 173
Jonathan Lin Avatar answered Nov 09 '22 20:11

Jonathan Lin


http://www.andygup.net/easily-find-image-type-in-javascript/

I think you may get some help from this page.

like image 44
Seven Avatar answered Nov 09 '22 18:11

Seven