最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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

<img src="==">

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.

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.

Share Improve this question edited Jul 15, 2015 at 7:39 sbedulin asked Jul 9, 2015 at 9:51 sbedulinsbedulin 4,3421 gold badge25 silver badges34 bronze badges 15
  • What do you mean by "image type"? Mime type? – PeeHaa Commented Jul 9, 2015 at 9:58
  • Would be great to have the Mime type, but the part which is usually a file extension is also enough (gif, png, jpeg, etc. en.wikipedia.org/wiki/Image_file_formats). – sbedulin Commented Jul 9, 2015 at 10:09
  • HTML5 only: htmlgoodies.com/html5/tutorials/… – somethinghere Commented Jul 9, 2015 at 10:12
  • @somethinghere I don't have <input type="file" /> with a File list – sbedulin Commented Jul 9, 2015 at 10:16
  • I don't think you need an input to use filereader, but I have used it once a long time ago. – somethinghere Commented Jul 9, 2015 at 10:18
 |  Show 10 more comments

2 Answers 2

Reset to default 14

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")

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

I think you may get some help from this page.

发布评论

评论列表(0)

  1. 暂无评论