JAVA讀取Oracle中的blob圖片字段並顯示

整個流程分爲四步,鏈接oracle數據庫 -> 讀取blob圖片字段 -> 對圖片進行縮放 ->把圖片展現在jsp頁面上。 html

下面進行詳細描述: java

1. java鏈接Oracle

注:數據庫是Oracle10g版本爲10.2.0, 在數據庫中,圖片字段類型爲BLOB。 sql

 

java中一般使用的是經過jdbc驅動來鏈接數據庫,oracle也不例外,所以必須下載一個Oracle驅動的jdbc須要去網上進行下載,名稱爲 ojdbc14.jar。 數據庫

下載地址爲: oracle

http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc101040.html jsp

 

下載了驅動以後,能夠使用驅動裏提供的接口進行鏈接,具體代碼以下: 函數

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;
    /*圖片ID字段名*/
    private String strIDName;
   /*圖片字段名*/
    private String strImgName;
    /**
     * 加載java鏈接Oracle的jdbc驅動
     */
    public OracleQueryBean(){
        try{
            Class.forName(oracleDriverName);
        }catch(ClassNotFoundException ex){
            System.out.println("加載jdbc驅動失敗,緣由:" + ex.getMessage());
        }
    }
    /**
     * 獲取Oracle鏈接對象
     * @return Connection
     */
    public Connection getConnection(){
        try{
        //用戶名+密碼; 如下使用的Test就是Oracle裏的表空間
        //從配置文件中讀取數據庫信息
        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("請檢測配置文件中的數據庫信息是否正確." );
        }
        return this.myConnection;
    }
}

2. 讀取blob字段

 

在OracleQueryBean類中增長一個函數,來進行讀取,具體代碼以下: this

/**
     * 根據圖片在數據庫中的ID進行讀取
     * @param strID 圖片字段ID
     * @param w      須要縮到的寬度
     * @param h      須要縮到高度
     * @return
     */
   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("獲取圖片數據失敗,緣由:" + 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;
}

3. 縮放圖片

由於圖片的大小可能不一致,可是在頁面中輸出的大小須要統一,因此須要 spa

在OracleQueryBean類中增長一個函數,來進行縮放,具體代碼以下: code


/**
     * 縮小或放大圖片
     * @param data   圖片的byte數據
     * @param w      須要縮到的寬度
     * @param h      須要縮到高度
     * @return       縮放後的圖片的byte數據
     */
    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);
            //原始顏色
            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis, bid);
           
            //轉換成byte字節
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bid, "jpeg", baos);
            newdata = baos.toByteArray();
           
    }catch(IOException e){ 
         e.printStackTrace(); 
    } 
    return newdata;
}

4. 展現在頁面

頁面使用OracleQueryBean來根據用戶提供的圖片id進行查詢,在讀取並進行縮放後,經過jsp頁面進行展現,具體代碼以下:

<%@ page language="java" contentType="text/html;;charset=gbk" %>
<jsp:useBean id="OrcleQuery" scope="page" class="HLFtiDemo.OracleQueryBean" />
<%
    response.setContentType("image/jpeg");
    //圖片在數據庫中的 ID
    String strID = request.getParameter("id");
    //要縮略或放大圖片的寬度
    String strWidth = request.getParameter("w");
    //要縮略或放大圖片的高度
    String strHeight = request.getParameter("h");
    byte[] data = null;
    if(strID != null){
        int nWith = Integer.parseInt(strWidth);
        int nHeight = Integer.parseInt(strHeight);
        //獲取圖片的byte數據
        data = OrcleQuery.GetImgByteById(strID, nWith, nHeight);
        ServletOutputStream op = response.getOutputStream();       
       op.write(data, 0, data.length);
       op.close();
       op = null;
        response.flushBuffer();
        //清除輸出流,防止釋放時被捕獲異常
        out.clear();
        out = pageContext.pushBody();
    }
%>
相關文章
相關標籤/搜索