Displaying Images from the Database using Java and MySQL

Dear all,
I was stored the gif/jpg image into the MySQL Database as a buffered image.
But when i was retrive the image from database and display in jsp page, it will not working well.
The image is not displaying.
The content get from the database, but it’s type is mismatch i think.
Here are the code i was using.

FOR UPLOADING IMAGE
<%@page contentType=“text/html”%>
<%@page pageEncoding=“UTF-8”%>
<%@ page language=“java” %>
<%@ page import=“java.awt.image."%>
<%@ page import="java.io.
”%>
<%@ page import=“java.sql."%>
<%@ page import=“java.io.File”%>
<%@ page import=“javax.imageio.ImageIO”%>
<%@ page import="java.awt.image.BufferedImage,java.util.
”%>
<%@ page import=“java.awt."%>
<%@ page import="java.util.
,com.oreilly.servlet.MultipartRequest”%>
<%
/* The Following Code is Used To Insert An Image Into Database /
String filename=“”;
try
{
//Download com.oreilly package
MultipartRequest multi= new MultipartRequest(request,“.”,5
1024*1024);
Enumeration files=multi.getFileNames();
File f=null;
while(files.hasMoreElements())
{
String name=(String)files.nextElement();
filename=multi.getFilesystemName(name);
String type=multi.getContentType(name);
f=multi.getFile(name);
System.out.println("The File is "+f);
}
Connection con=null;
String userName=“root”;
String password = “veradis”;
Class.forName(“com.mysql.jdbc.Driver”);
con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/sample”,userName,password);
Statement stmt = con.createStatement();
InputStream is = new FileInputStream(f);
byte b=new byte[is.available()];
is.read(b);
int flag=0;
try
{
String sql = “INSERT into tbl_image(image) values('” + b + “')”;
System.out.println(sql);
stmt.execute(sql);
flag=1;
}
catch(Exception e)
{
System.out.println("SQL Exception : " + e);
}
if(flag==1)
{
System.out.println(“Query Executed Successfully”);
}

stmt.close();
}
catch(Exception e)
{
System.out.println(e);
}
out.println(“The Image is Added into Database”);
%>

and FOR RETRIVE AND DISPLAY FROM THE DATABASE
<%@page contentType=“text/html”%>
<%@page pageEncoding=“UTF-8”%>
<%@ page language=“java” %>
<%@ page import=“java.awt.image."%>
<%@ page import="java.io.
”%>
<%@ page import=“java.sql."%>
<%@ page import="javax.servlet.
”%>
<%@ page import=“javax.servlet.http."%>
<%@ page import=“java.io.File”%>
<%@ page import=“javax.imageio.ImageIO”%>
<%@ page import="java.awt.image.BufferedImage,java.util.
”%>
<%@ page import=“java.awt.*”%>
<html>
<head><title>JSP Page</title></head>
<body>
<%
try
{
javax.servlet.http.HttpServletResponse res=null;;
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream in = null;
OutputStream os = null;
Blob blob = null;
String text;
text=request.getParameter(“text”);
Class.forName(“com.mysql.jdbc.Driver”);
conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/sample”,“root”,“veradis”);
final String query = “SELECT image FROM tbl_image”;
conn.setAutoCommit(false);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
int i=1;
if(rs.next())
{
String len1 = rs.getString(“image”);
int len = len1.length();
byte b = new byte[len];
in = rs.getBinaryStream(“image”);
int index = in.read(b, 0, len);
OutputStream outImej = new FileOutputStream(“C:/Documents and Settings/Tamil/Desktop/photo/img”+i+“.JPG”);
while (index != -1)
{
outImej.write(b, 0, index);
index = in.read(b, 0, len);
System.out.println(“==========================”);
System.out.println(index);
System.out.println(outImej);
System.out.println(“==========================”);
}
outImej.close();
i++;
}
else
{
returnValue = 1;
}
}
catch(Exception e)
{
out.println("SQLEXCEPTION : " +e);
}
%>
</body>
</html>

If i can run this code the image column was displayed as empty.
If anyone can know how to solve this problem, please help me.

Regards
Tamilvanan

few Thoughts: -

  1. What is the “Data Type” of the image Column in database? (Should use “Blob” as a column type to store the Binary data)
  2. Did you tried to Check the Table and see whether the Image is really stored in the db column?

Go through this Link, it will help you http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertpicturetoMySQL.htm

Hai sumit1001, Thanks for your reply.

I have go through the code. By using those code, the image was retriving as a byte. But for inserting the image was inserted as a Binary data.

Yes that code was retrive the Image as byte, but the values are displaying 1like [B][B@1415de6[/B].

But i need to display as image. The Image will be retriving from database as a image file.

Please help me with this.

Thanks

Tamilvanan

Did you look at the examples listed there at the Bottom of the page (http://www.java2s.com/Code/Java/Data...uretoMySQL.htm )?

http://www.java2s.com/Code/Java/Database-SQL-JDBC/Materializebinarydataontoclient.htm
http://www.java2s.com/Code/Java/Database-SQL-JDBC/BlobJDBCdealswithBinaryData.htm
http://www.java2s.com/Code/Java/Database-SQL-JDBC/BlobandJDBCImage.htm
http://www.java2s.com/Code/Java/Database-SQL-JDBC/BlobImage2.htm
http://www.java2s.com/Code/Java/Database-SQL-JDBC/Blobimage3.htm

I am sure one of these link will solve your problem

On the other way round I hope you are not trying to Display the image directly from database in a JSP. if so than this will not work. You have to use a specialized servlet which does this job. something like this: -
<img src=“<%=request.getContextPath()+‘/servlet/PictureSevlet?pictureID=’+pictureID%>”

Hai sumit1001, Thanks for your reply.

It’s working fine.
I am using the response.getOutputStream() method, then it’s working well.
I have get the image from database and write it as follows

InputStream sImage;
sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType(rs.getString(“type”));

Then I need to Reduce the time for uploading image and Retrive the Image from database.

If i will upload the large size of image, it’s size id different, so when i upload those type of image, i need to load the page with the less time.

Please help me with this.

Regards
Tamilvanan

I am not able to understand your concern.
Do you want to reduce the time for the image uploading?

if yes than there are number of factors which could affect this: -

  1. Size of image
  2. Datasource used to store the uploaded image
  3. Check for Connection leaks.
  4. Performance of database for retrieving and Storing the Large Objects.

try
{
javax.servlet.http.HttpServletResponse res=null;;
int returnValue = 0;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

String text;
text=request.getParameter(“text”);
Class.forName(“oracle.jdbc.driver.OracleDriver”);
con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:ghdb2”, “scott”, “ghdb”);
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT image FROM photo where autono= ‘7’ ");
int i=1;
if(rs.next())
{
Blob len1 = rs.getBlob(“image”);
int len = (int)len1.length();
byte b = new byte[len];
InputStream readImg = rs.getBinaryStream(1);

    int index=readImg.read(b, 0, len);
    System.out.println("index"+index);
    stmt.close();
    response.reset();
    response.setContentType("image/jpg");
    response.getOutputStream().write(b,0,len);
    response.getOutputStream().flush();

}
else
{
returnValue = 1;
}
}
catch(Exception e)
{
out.println("SQLEXCEPTION : " +e);
}
%>
</body>
</html>

I have write this code for view image from db but it gives result like
http:-serverip:8084-match-view.jsp

in above match is my project name and view.jsp is gave result.
I am new to use jsp/servlet.
Any one have any idea then let me know.