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

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

下面進行詳細描述:

1. java連接Oracle

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

java中通常使用的是通過jdbc驅動來連接數據庫,oracle也不例外,因此必須下載一個Oracle驅動的jdbc需要去網上進行下載,名稱爲 ojdbc14.jar。

下載地址爲:

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

下載了驅動之後,可以使用驅動裏提供的接口進行連接,具體代碼如下:

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連接Oraclejdbc驅動

     */

    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類中增加一個函數,來進行讀取,具體代碼如下:

/**

     * 根據圖片在數據庫中的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. 縮放圖片

因爲圖片的大小可能不一致,但是在頁面中輸出的大小需要統一,所以需要

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

/**

     * 縮小或放大圖片

     * @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();

    }

%>

5. OracleQueryBean查詢類的整體代碼

OracleQueryBean.java文件代碼如下所示:

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連接Oraclejdbc驅動

     */

    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;

    }

    /**

     * 根據圖片在數據庫中的ID進行讀取

     * @param strID 圖片字段ID

     * @param w      需要縮到的寬度

     * @param h      需要縮到高度

     * @return       縮放後的圖片的byte數據

     */

    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;

    }

   

    /**

     * 根據圖片在數據庫中的ID進行讀取,顯示原始大小的圖片

     * @param    strID   圖片字段ID

     * @return   讀取後的圖片byte數據

     */

    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("獲取圖片數據失敗,原因:" + e.getMessage());

                }

            }

            System.out.println(myStringBuffer.toString());

            myConnection.commit();

            myConnection.close();

        } catch (SQLException ex) {

            System.out.println(ex.getMessage());

        }

        return data;

    }

   

    /**

     * 縮小或放大圖片

     * @param data   圖片的byte數據

     * @param w      需要縮到的寬度

     * @param h      需要縮到高度

     * @return

     */

    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;

    }

}

發佈了32 篇原創文章 · 獲贊 39 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章