ByteArray to image in JSP
I got a mainframe transaction that returns me a TIFF image, on the fly i convert it to jpeg. After convertin it(im sure its working, i can save the image), i store the image in a byte array. Now i have the byte array in my JSP, but i dunno how to show the image in the browser! Anyone have any clue?
Thx a lot
I use this. You may be able to tinker about with it to do what you want.
hope it helps.
import java.sql.*;
import java.io.*;
import java.util.*;
import java.awt.*;
Import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Images{
/*-
*Get the Blob image
**/
static String req = "" ;
static ResultSet rset;
static Connection conn;
static Statement stmt;
static byte[] imgData = null;
static Image image;
public static synchronized byte[] getPhoto (int iNumPhoto) throws Exception, SQLException{
try{
System.out.println("Photo ID=" + iNumPhoto);
conn = DBConnectionClass.getConnection();
conn.setAutoCommit (false);
Blob img ;
stmt = conn.createStatement ();
// Query
req = "Select image From Images Where ImageID = " + iNumPhoto ;
rset = stmt.executeQuery ( req );
while (rset.next ())
{
img = rset.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
}
} catch (SQLException exception){
System.out.println("ERROR in getPhoto(" + iNumPhoto + "): " +
"Error cause by query Statement.");
System.out.println(exception.toString());
System.out.println(req);
} finally {
try{
stmt.close();
conn.close();
}catch (SQLException ignored){}
}
System.out.println("imgData:" + imgData);
System.out.println("imgData:" + imgData.toString());
if(imgData == null){
return null ;
}else{
return imgData ;
}
}
}
Obviously there is probably a better way of doing things, I'm only learning myself. It does work though, Ive used it myself.
then in your jsp, use
<jsp:useBean id="img" class="fxs.ReadFileIntoByteArray" scope="session" />
<jsp:useBean id="photo" class="fxs.Images" scope="session" />
<%
try{
// get the image from the database
byte[] imgData = photo.getPhoto(iNumPhoto) ;
response.setContentType("image/jpeg");
OutputStream o = response.getOutputStream();
if(imgData == null){
try{
byte[] newImgData;
newImgData = img.getBytes("/images/noImage.gif");
o.write(newImgData);
}catch(Exception e){
System.out.println(e.toString());
}
}else{
// display the image
o.write(imgData);
}
o.flush();
o.close();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
// Close the connection ;
}
Keytha at 2007-7-14 20:30:55 >
