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: .
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.
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/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.
Share Improve this question edited Apr 16, 2021 at 18:54 Machavity♦ 31.7k27 gold badges95 silver badges105 bronze badges asked Apr 24, 2012 at 17:10 sbrsbr 4,8435 gold badges45 silver badges51 bronze badges 3- 2 Like, a base 64 decoder ostermiller/calc/encode.html and a tool to give you the type from binary data htmlgoodies./html5/tutorials/… ? – Jamie Treworgy Commented Apr 24, 2012 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 ordata: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 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 Commented Apr 24, 2012 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 Commented Apr 25, 2012 at 19:54
1 Answer
Reset to default 3There's lots of javascript base64 decoders, (related question), just decode the first 4 or 5 letters and they should contain the filetype.