It's not a secret anymore!
The moose likes Java in General and the fly likes Displaying image from a BLOB stored in DB Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Displaying image from a BLOB stored in DB" Watch "Displaying image from a BLOB stored in DB" New topic

Displaying image from a BLOB stored in DB

Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 782


I store the bytes of an image inside a BLOB field in a database.
I want to be able to display this image beside the other text fields from the same table. One idea is to use a Servlet to deliver the mime type and then spit the bytes to the browser. But to do this, I would have to open a new window.

Since I don't want to serialize the BLOB to an image file; how can I achieve this ? I'm not sure how to use the HTML IMG tag to do this. Thanks

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15094

What database are you using; Oracle, MySQL, something else?

BLOBs unfortunately don't work exactly the same on all databases. You'll find examples of how to work with BLOBs in Java if you search Google for "java oracle blob", for example.

Or do you already know how to read the BLOB, but you just want to know how to send it to the client from your web app?

Why do you think you would need to open a new window if you do it with a servlet?

Just include an IMG tag in your HTML page with an URL that points to the servlet that retrieves and sends out the image, instead of the URL of an image file.
[ June 13, 2006: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 782

I am using MySql5. My problem was actually sending it to the client. I will try your solution about pointing the img tag to the servlet. Thanks Jesper.
Jaime M. Tovar
Ranch Hand

Joined: Mar 28, 2005
Posts: 133
Create the servlet you were talking about. Then inside the jsp use something like <img src=�/your_app/your_servlet?some_parameters�> it will show the image as any other non dynamic you have in your site. Also you can pass parameters in session. In fact the browser doesn�t knows it isn�t a static image, it only cares about the tag calling it and the mime type. Take into account that the image in the blob must be a web compliant, lets say it will be easier to show a jpg from the database than to show a bmp, cause not every browser knows how to deal with bmp.

She will remember your heart when men are fairy tales in books written by rabbits.<br /> As long as there is duct tape... there is also hope.
I agree. Here's the link:
subject: Displaying image from a BLOB stored in DB
It's not a secret anymore!