File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JSP and the fly likes Streaming an image to the browser Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "Streaming an image to the browser" Watch "Streaming an image to the browser" New topic

Streaming an image to the browser

M Burke
Ranch Hand

Joined: Jun 25, 2004
Posts: 397
I have image files that are BLOBS in a database, and I can load them into server memory (using a sql select).

I want to then display the image in the browser. I think response.getOutputStream() is involved somehow since JSPWriter is for text data. I am not sure if I can pass a byte arry directly into the html img tag (thinking outloud).

Any ideas?
Ben Souther

Joined: Dec 11, 2004
Posts: 13410


Look for SimpleStream

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
M Burke
Ranch Hand

Joined: Jun 25, 2004
Posts: 397
Hi Ben,
I wrote some code based on your example, but it does not work quite right.
The image fills the entire browser window and the html is somehow kicked out of the response buffer.

I place this code in the response html:
<img border="1" align="middle" src="profile001.jpg">

This code is called by a servlet to inject the picture into the response stream. It does send the pic to the browser, but it steps all over the html used to display it:

private void streamImg(HttpServletResponse response)throws ServletException, IOException{

" inline; filename=" + "profile001.jpg");

BufferedInputStream bin = new BufferedInputStream(new FileInputStream("C:/a/profile001.jpg"));
ServletOutputStream sos = response.getOutputStream();

byte[] buffer = new byte[4 * 1024];

int data = 0;
while((data = != -1){
sos.write(buffer, 0, data);

Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63548

Are you sending the HTML and the image in the same response?

Your HTML should be the only thing sent in the first reponse, and the src attribute of the <img> tag should reference a servlet that only sends the image data.

[Asking smart questions] [About Bear] [Books by Bear]
M Burke
Ranch Hand

Joined: Jun 25, 2004
Posts: 397
Oh, I see Bear, thanks. It works now with a seperate servlet servicing the img tag
I agree. Here's the link:
subject: Streaming an image to the browser
jQuery in Action, 3rd edition