Saturday, August 9, 2008

Java Programming - How to get photo field of database and display it in Java application?

How to get photo field of database and display it in Java application?
Usually data type from database is binary. We must convert data type into java.awt.Image or javax.swing.ImageIcon to display it in Java applications.

Example:

public class Photo
{
public ImageIcon getPhoto(String studentId)
{
ImageIcon photo = null;
try
{
Class.forName(.....).newInstance();
Connection con = DriverManager.getConnection(.......);

String sql = "SELECT * FROM STUDENT WHERE studentId = '" + studentId +"'";

Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);

if (rs.next())
{
Blob image = rs.getBlob("File_Photo");

InputStream input = image.getBinaryStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();

byte[] readByte = new byte[1024];
int i = 0;
while ((i = input.read(readByte)) != -1)
{
output.write(readByte, 0, i);
}
byte[] result = output.toByteArray();
input.close();
output.close();

photo = new ImageIcon(result);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, "Error!\n" + e);
}

return (photo);
}
}