9

I have different types of image content in base64 format in javascript, like:

a png file: "iVBORw0KGgoAAAANSUhEUgAABQAAAAL4CAYAAAAkgloNAAAgA......."

a jpeg file: "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDA......"

similarly, there can be other images like GIF, BMP, etc.

I need a way to determine the image type based on the content. I understand there are headers for each file type and I can refer it to determine the image content type. Example Reference: http://en.wikipedia.org/wiki/Portable_Network_Graphics#Technical_details.

But does anyone know of a library or other technique that will do the trick in a more smarter way? I can use any of the HTML5 features if required.

The main intent is to render the image on the screen. For that I use dataURI pattern, . I have image content, all I need is to put the right value in the "data:image/png" part of the url.

Machavity
  • 30,841
  • 27
  • 92
  • 100
sbr
  • 4,735
  • 5
  • 43
  • 49
  • 2
    Like, a base 64 decoder http://ostermiller.org/calc/encode.html and a tool to give you the type from binary data http://www.htmlgoodies.com/html5/tutorials/determine-an-images-type-using-the-javascript-filereader.html#fbid=qYZntLVXSZU ? – Jamie Treworgy Apr 24 '12 at 17:13
  • 2
    Modern browsers will figure out what type an image is on their own, they don't rely on file extensions or mime types. Try adding `data:image/png` to a jpeg or `data:image/gif` to a png, it should still render fine. As for checking the header for the filetype, that's the accepted way of doing it for [any file](http://www.garykessler.net/library/file_sigs.html) in scenarios where the mime type or file name is not available (and sometimes even when it is available), nothing wrong with it at all. – Dagg Nabbit Apr 24 '12 at 20:45
  • Just checked FF,IE,Chrome with data:image/png for 3 types of image files- jpg,gif and bmp; and they render fine with mime type="image/png", used latest versions of all these browsers. – sbr Apr 25 '12 at 19:54

1 Answers1

2

There's lots of javascript base64 decoders, (related question), just decode the first 4 or 5 letters and they should contain the filetype.

Community
  • 1
  • 1
hobberwickey
  • 6,118
  • 4
  • 28
  • 29