Java method to read a Blob object image from a database and display it

  • 2020-04-01 03:39:55
  • OfStack

This article illustrates how Java can read a Blob object image from a database and display it. Share with you for your reference. The specific implementation method is as follows:

The first method:

The general approach is to read the Blob stream from the database and write it to the page:

Connection conn = DBManager.getConnection();
  String sql = "SELECT picture FROM teacher WHERE id=1";
  PreparedStatement ps = null;
  ResultSet rs = null;
  InputStream is = null;
  OutputStream os = null;
  try {
   ps = conn.prepareStatement(sql);
   rs = ps.executeQuery();
 
   if(rs.next()){
    is = rs.getBinaryStream(1);
   }
 
   response.setContentType("text/html");
   os = response.getOutputStream();
 
   int num;
   byte buf[] = new byte[1024];
 
   while(   (num=is.read(buf))!=-1   ){
    os.write(buf, 0, num);
   }
 
  } catch (SQLException e) {
   e.printStackTrace();
  }
 
  try {
   is.close();
   os.close();
   rs.close();
   ps.close();
  } catch (SQLException e) {
   e.printStackTrace();
}

 
On the page:
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<img name="pic" src="<%=basePath+"servlet/DownloadAsStream"%>"/>

 
Get things done.

The second method:

The whole process is divided into four steps, connecting oracle database -> Read blob image field -> Zoom the picture -> Display the image on the JSP page.

import java.sql.*;
import java.io.*;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.AffineTransformOp;
import java.awt.geom.AffineTransform;
 
public class OracleQueryBean {
    private final String oracleDriverName = "oracle.jdbc.driver.OracleDriver";
    private Connection myConnection = null;
  
    private String strTabName;
  
    private String strIDName;
 
    private String strImgName;
  
    public OracleQueryBean(){
        try{
            Class.forName(oracleDriverName);
        }catch(ClassNotFoundException ex){
            System.out.println(" loading jdbc Drive failure , why :" + ex.getMessage());
        }
    }
  
    public Connection getConnection(){
        try{
        //User name + password; The following Test is the table space in Oracle
        //Reads the database information from the configuration file
        GetPara oGetPara = new GetPara();
        String strIP = oGetPara.getPara("serverip");
        String strPort = oGetPara.getPara("port");
        String strDBName = oGetPara.getPara("dbname");
        String strUser = oGetPara.getPara("user");
        String strPassword = oGetPara.getPara("password");
      
        this.strTabName = oGetPara.getPara("tablename");
        this.strIDName = oGetPara.getPara("imgidname");
        this.strImgName = oGetPara.getPara("imgname");
      
        String oracleUrlToConnect ="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName;
            this.myConnection = DriverManager.getConnection(oracleUrlToConnect, strUser, strPassword);
        }catch(Exception ex){
            System.out.println("Can not get connection:" + ex.getMessage());
            System.out.println(" Check that the database information in the configuration file is correct ." );
        }
        return this.myConnection;
    }
}

2. Read the blob field
 
Add a function in the OracleQueryBean class to read, the specific code is as follows:

public byte[] GetImgByteById(String strID, int w, int h){
    //System.out.println("Get img data which id is " + nID);
    if(myConnection == null)
         this.getConnection();
    byte[] data = null;
    try {
            Statement stmt = myConnection.createStatement();
            ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID);
          
            StringBuffer myStringBuffer = new StringBuffer();
            if (myResultSet.next()) {
                java.sql.Blob blob = myResultSet.getBlob(this.strImgName);
                InputStream inStream = blob.getBinaryStream();
                try {
                    long nLen = blob.length();
                    int nSize = (int) nLen;
                    //System.out.println("img data size is :" + nSize);
                    data = new byte[nSize];
                    inStream.read(data);
                    inStream.close();
                } catch (IOException e) {
                    System.out.println(" Failed to obtain image data , why :" + e.getMessage());
                }
              
                data = ChangeImgSize(data, w, h);
            }
            System.out.println(myStringBuffer.toString());
            myConnection.commit();
            myConnection.close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return data;
}

Scale the picture

Because the size of the image may not be uniform, but the size of the output on the page needs to be uniform, so yes
Add a function in the OracleQueryBean class to scale, the specific code is as follows:

private byte[] ChangeImgSize(byte[] data, int nw, int nh){
    byte[] newdata = null;
    try{
         BufferedImage bis = ImageIO.read(new ByteArrayInputStream(data));
            int w = bis.getWidth();
            int h = bis.getHeight();
            double sx = (double) nw / w;
            double sy = (double) nh / h;
            AffineTransform transform = new AffineTransform();
            transform.setToScale(sx, sy);
            AffineTransformOp ato = new AffineTransformOp(transform, null);
            //Original color
            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis, bid);
          
            //Convert to byte byte
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bid, "jpeg", baos);
            newdata = baos.toByteArray();
          
    }catch(IOException e){
         e.printStackTrace();
    }
    return newdata;
}

4. Display on the page
The page USES the OracleQueryBean to query according to the image id provided by the user. After reading and scaling, the page is displayed through the JSP page. The specific code is as follows:

<%@ page language="java" contentType="text/html;;charset=gbk" %>
<jsp:useBean id="OrcleQuery" scope="page" class="HLFtiDemo.OracleQueryBean" />
<%
    response.setContentType("image/jpeg");
    //Image in the database ID
    String strID = request.getParameter("id");
    //
the width of the image to thumbnail or enlarge     String strWidth = request.getParameter("w");
    //Height
to thumbnail or enlarge the image     String strHeight = request.getParameter("h");
    byte[] data = null;
    if(strID != null){
        int nWith = Integer.parseInt(strWidth);
        int nHeight = Integer.parseInt(strHeight);
        //Gets the image's byte data
        data = OrcleQuery.GetImgByteById(strID, nWith, nHeight);
        ServletOutputStream op = response.getOutputStream();      
       op.write(data, 0, data.length);
       op.close();
       op = null;
        response.flushBuffer();
        //Clear the output stream to prevent the exception
from being caught when it is released         out.clear();
        out = pageContext.pushBody();
    }
%>

5. The whole code of the querybean query class

The code for the oracle querybean.java file is as follows:

import java.sql.*;
import java.io.*;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.AffineTransformOp;
import java.awt.geom.AffineTransform;
 
public class OracleQueryBean {
    private final String oracleDriverName = "oracle.jdbc.driver.OracleDriver";
 
    private Connection myConnection = null;
  
  
    private String strTabName;
  
    private String strIDName;
  
    private String strImgName;
  
    public OracleQueryBean(){
        try{
            Class.forName(oracleDriverName);
        }catch(ClassNotFoundException ex){
            System.out.println(" loading jdbc Drive failure , why :" + ex.getMessage());
        }
    }
  
    public Connection getConnection(){
        try{
        //User name + password; The following Test is the table space in Oracle
        //Reads the database information from the configuration file
        GetPara oGetPara = new GetPara();
        String strIP = oGetPara.getPara("serverip");
        String strPort = oGetPara.getPara("port");
        String strDBName = oGetPara.getPara("dbname");
        String strUser = oGetPara.getPara("user");
        String strPassword = oGetPara.getPara("password");
      
        this.strTabName = oGetPara.getPara("tablename");
        this.strIDName = oGetPara.getPara("imgidname");
        this.strImgName = oGetPara.getPara("imgname");
      
        String oracleUrlToConnect ="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName;
            this.myConnection = DriverManager.getConnection(oracleUrlToConnect, strUser, strPassword);
        }catch(Exception ex){
            System.out.println("Can not get connection:" + ex.getMessage());
            System.out.println(" Check that the database information in the configuration file is correct ." );
        }
        return this.myConnection;
    }
  
    public byte[] GetImgByteById(String strID, int w, int h){
    //System.out.println("Get img data which id is " + nID);
    if(myConnection == null)
         this.getConnection();
    byte[] data = null;
    try {
            Statement stmt = myConnection.createStatement();
            ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID);
          
            StringBuffer myStringBuffer = new StringBuffer();
            if (myResultSet.next()) {
                java.sql.Blob blob = myResultSet.getBlob(this.strImgName);
                InputStream inStream = blob.getBinaryStream();
                try {
                    long nLen = blob.length();
                    int nSize = (int) nLen;
                    //System.out.println("img data size is :" + nSize);
                    data = new byte[nSize];
                    inStream.read(data);
                    inStream.close();
                } catch (IOException e) {
                    System.out.println(" Failed to obtain image data , why :" + e.getMessage());
                }
              
                data = ChangeImgSize(data, w, h);
            }
            System.out.println(myStringBuffer.toString());
            myConnection.commit();
            myConnection.close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return data;
    }     public byte[] GetImgByteById(String strID){
    //System.out.println("Get img data which id is " + nID);
    if(myConnection == null)
         this.getConnection();
    byte[] data = null;
    try {
            Statement stmt = myConnection.createStatement();
            ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID);
          
            StringBuffer myStringBuffer = new StringBuffer();
            if (myResultSet.next()) {
                java.sql.Blob blob = myResultSet.getBlob(this.strImgName);
                InputStream inStream = blob.getBinaryStream();
                try {
                    long nLen = blob.length();
                    int nSize = (int) nLen;
                    data = new byte[nSize];
                    inStream.read(data);
                    inStream.close();
                } catch (IOException e) {
                    System.out.println(" Failed to obtain image data , why :" + e.getMessage());
                }
            }
            System.out.println(myStringBuffer.toString());
            myConnection.commit();
            myConnection.close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return data;
    }     private byte[] ChangeImgSize(byte[] data, int nw, int nh){
    byte[] newdata = null;
    try{
         BufferedImage bis = ImageIO.read(new ByteArrayInputStream(data));
            int w = bis.getWidth();
            int h = bis.getHeight();
            double sx = (double) nw / w;
            double sy = (double) nh / h;
            AffineTransform transform = new AffineTransform();
            transform.setToScale(sx, sy);
            AffineTransformOp ato = new AffineTransformOp(transform, null);
            //Original color
            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis, bid);         
            //Convert to byte byte
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bid, "jpeg", baos);
            newdata = baos.toByteArray();
    }catch(IOException e){
         e.printStackTrace();
    }
    return newdata;
    }
}

Here is my example of a blob image being read from storage

import java.sql.*;    
import java.io.*;  
public class InsertPhoto { 
    public static void main(String[] args) throws Exception{ 
            Class.forName("com.mysql.jdbc.Driver");   
           Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/wiseweb?user=root&password=root");   
           File f = new File("e:/123.jpg");   
           FileInputStream fis = new FileInputStream(f);   
           String sql = "insert into photo(photo,photoName) values(?,?)";   
           PreparedStatement pstmt = con.prepareStatement(sql);   
           pstmt.setBinaryStream(1,fis,(int)f.length());   
           pstmt.setString(2, " The test image "); 
           pstmt.executeUpdate();   
           fis.close();   
           pstmt.close();   
           con.close();  
    } 
}

import java.awt.image.BufferedImage;  
import java.io.BufferedInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
 
import javax.imageio.ImageIO; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import com.sun.image.codec.jpeg.JPEGCodec; 
import com.sun.image.codec.jpeg.JPEGImageEncoder;  public class ReadPhoto extends HttpServlet{ 
 
    private static final long serialVersionUID = 1L; 
     
    public void doGet(HttpServletRequest request, HttpServletResponse response){ 
        if(request.getParameter("id") != null){ 
            response.setContentType("image/jpeg"); 
            try { 
                InputStream is = query_getPhotoImageBlob(Integer.parseInt(request.getParameter("id"))) ; 
                if(is != null){ 
                    is = new BufferedInputStream(is) ; 
                    BufferedImage bi = ImageIO.read(is) ; 
                    OutputStream os = response.getOutputStream() ; 
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os) ; 
                    encoder.encode(bi); 
                    os.close();   
                    is.close();   
                } 
            } catch(IOException e){ 
                e.printStackTrace(); 
            }catch (NumberFormatException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } catch (ClassNotFoundException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } catch (SQLException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } 
        } 
    } 
     
    public static InputStream query_getPhotoImageBlob(int id) throws ClassNotFoundException, SQLException{   
           String sql = "select photo from photo where id="+id;   
           Connection con = null;   
           Statement stmt = null;   
           ResultSet rs = null;   
           InputStream result = null;   
           try {   
            Class.forName("com.mysql.jdbc.Driver");   
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/wiseweb?user=root&password=root");    
            stmt = con.createStatement();   
            rs = stmt.executeQuery(sql);   
            if (rs.next())   
            result = rs.getBlob("photo").getBinaryStream();   
           } catch (SQLException e) {   
            // TODO: handle exception   
            System.err.println(e.getMessage());   
           }finally{   
               rs.close();   
               stmt.close();   
               con.close();  
           }   
           return result;   
        }  
}

JSP shows

<img style="width:320px;height:240px" src="<%=basePath%>/genImage?id=3"/>

Configuration in web.xml

<servlet>  
    <servlet-name>genImage</servlet-name> 
    <servlet-class>ReadPhoto</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>genImage</servlet-name> 
    <url-pattern>/genImage</url-pattern> 
</servlet-mapping>

I hope this article has been helpful to your Java programming.


Related articles: