Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display images stored in database as a blob, in webpage

I want to display a image in webpage , which is stored in database as blob type. I am storing a image as binary/image type in database successfully. But how can i display it in webpage. I am getting a image as something like symbols(�����JFIF�������fExif��II*���������>) when i retrieve from the database.

like image 874
R J. Avatar asked Feb 19 '23 16:02

R J.


2 Answers

You should convert image data to base64 and then write to response, for example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAM0AAAD
 NCAMAAAAsYgRbAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5c
 cllPAAAABJQTFRF3NSmzMewPxIG//ncJEJsldTou1jHgAAAARBJREFUeNrs2EEK
 gCAQBVDLuv+V20dENbMY831wKz4Y/VHb/5RGQ0NDQ0NDQ0NDQ0NDQ0NDQ
 0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0PzMWtyaGhoaGhoaGhoaGhoaGhoxtb0QGho
 aGhoaGhoaGhoaGhoaMbRLEvv50VTQ9OTQ5OpyZ01GpM2g0bfmDQaL7S+ofFC6x
 v3ZpxJiywakzbvd9r3RWPS9I2+MWk0+kbf0Hih9Y17U0nTHibrDDQ0NDQ0NDQ0
 NDQ0NDQ0NTXbRSL/AK72o6GhoaGhoRlL8951vwsNDQ0NDQ1NDc0WyHtDTEhD
 Q0NDQ0NTS5MdGhoaGhoaGhoaGhoaGhoaGhoaGhoaGposzSHAAErMwwQ2HwRQ
 AAAAAElFTkSuQmCC" alt="beastie.png" /> 

http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/

Or you can make a link to server script which return header with content type of any image and write image data directly to response.

like image 94
testCoder Avatar answered Feb 21 '23 06:02

testCoder


Here's the code I used when I had to render a binary image from the database (SQL Server) into a html page using Ajax

stm = conn.prepareStatement("SELECT IMAGE FROM TABLE" );
rs = stm.executeQuery();
return rs

The raw rs is then received using ajax(stored in the "response"):

        $.post('./getImagePage.jsp', {
            action : 'getImage'
        }, function(response) {         
            if (response != ''){                                                        
                var arrayBufferView = new Uint8Array( response[0].IMAGE);                                       
                var blob = new Blob( [ arrayBufferView ], { type: "image/jpg" } );
                var urlCreator = window.URL || window.webkitURL;
                var imageUrl = urlCreator.createObjectURL( blob );                                  
                var img = document.querySelector("#fotoMb");
                img.src = imageUrl;                     
        });     

And the HTML:

<img id="fotoMb" style="border:5px solid;">
like image 21
Marcelo Carvalho Nascimento Avatar answered Feb 21 '23 07:02

Marcelo Carvalho Nascimento