最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java從數(shù)據(jù)庫中讀取Blob對象圖片并顯示的方法

 更新時(shí)間:2015年02月04日 12:01:20   作者:Benjamin_whx  
這篇文章主要介紹了Java從數(shù)據(jù)庫中讀取Blob對象圖片并顯示的方法,實(shí)例分析了Java讀取數(shù)據(jù)庫中Blob對象圖片的技巧與操作方法,需要的朋友可以參考下

本文實(shí)例講述了Java從數(shù)據(jù)庫中讀取Blob對象圖片并顯示的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

第一種方法:

大致方法就是,從數(shù)據(jù)庫中讀出Blob的流來,寫到頁面中去:

復(fù)制代碼 代碼如下:
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();
}

 
在頁面中:
復(fù)制代碼 代碼如下:
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<img name="pic" src="<%=basePath+"servlet/DownloadAsStream"%>"/>

 
搞定。

第二種方法:

整個(gè)流程分為四步,連接oracle數(shù)據(jù)庫 -> 讀取blob圖片字段 -> 對圖片進(jìn)行縮放 ->把圖片展示在jsp頁面上。

復(fù)制代碼 代碼如下:
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("加載jdbc驅(qū)動(dòng)失敗,原因:" + ex.getMessage());
        }
    }
  
    public Connection getConnection(){
        try{
        //用戶名+密碼; 以下使用的Test就是Oracle里的表空間
        //從配置文件中讀取數(shù)據(jù)庫信息
        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("請檢測配置文件中的數(shù)據(jù)庫信息是否正確." );
        }
        return this.myConnection;
    }
}

2. 讀取blob字段
 
在OracleQueryBean類中增加一個(gè)函數(shù),來進(jìn)行讀取,具體代碼如下:

復(fù)制代碼 代碼如下:
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("獲取圖片數(shù)據(jù)失敗,原因:" + 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. 縮放圖片

因?yàn)閳D片的大小可能不一致,但是在頁面中輸出的大小需要統(tǒng)一,所以需要
在OracleQueryBean類中增加一個(gè)函數(shù),來進(jìn)行縮放,具體代碼如下:

復(fù)制代碼 代碼如下:
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);
          
            //轉(zhuǎn)換成byte字節(jié)
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bid, "jpeg", baos);
            newdata = baos.toByteArray();
          
    }catch(IOException e){
         e.printStackTrace();
    }
    return newdata;
}

4. 展示在頁面
頁面使用OracleQueryBean來根據(jù)用戶提供的圖片id進(jìn)行查詢,在讀取并進(jìn)行縮放后,通過jsp頁面進(jìn)行展示,具體代碼如下:

復(fù)制代碼 代碼如下:
<%@ page language="java" contentType="text/html;;charset=gbk" %>
<jsp:useBean id="OrcleQuery" scope="page" class="HLFtiDemo.OracleQueryBean" />
<%
    response.setContentType("image/jpeg");
    //圖片在數(shù)據(jù)庫中的 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數(shù)據(jù)
        data = OrcleQuery.GetImgByteById(strID, nWith, nHeight);
        ServletOutputStream op = response.getOutputStream();      
       op.write(data, 0, data.length);
       op.close();
       op = null;
        response.flushBuffer();
        //清除輸出流,防止釋放時(shí)被捕獲異常
        out.clear();
        out = pageContext.pushBody();
    }
%>

5. OracleQueryBean查詢類的整體代碼

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

復(fù)制代碼 代碼如下:
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("加載jdbc驅(qū)動(dòng)失敗,原因:" + ex.getMessage());
        }
    }
  
    public Connection getConnection(){
        try{
        //用戶名+密碼; 以下使用的Test就是Oracle里的表空間
        //從配置文件中讀取數(shù)據(jù)庫信息
        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("請檢測配置文件中的數(shù)據(jù)庫信息是否正確." );
        }
        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("獲取圖片數(shù)據(jù)失敗,原因:" + 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("獲取圖片數(shù)據(jù)失敗,原因:" + 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);
            //原始顏色
            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis, bid);         
            //轉(zhuǎn)換成byte字節(jié)
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bid, "jpeg", baos);
            newdata = baos.toByteArray();
    }catch(IOException e){
         e.printStackTrace();
    }
    return newdata;
    }
}

下面是我的存儲讀取blob圖片的案例

復(fù)制代碼 代碼如下:
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, "測試圖片"); 
           pstmt.executeUpdate();   
           fis.close();   
           pstmt.close();   
           con.close();  
    } 
}

復(fù)制代碼 代碼如下:
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顯示

復(fù)制代碼 代碼如下:
<img style="width:320px;height:240px" src="<%=basePath%>/genImage?id=3"/>

web.xml中配置

復(fù)制代碼 代碼如下:
<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>

希望本文所述對大家的Java程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • MybatisPlus 自定義.vm模板的生成

    MybatisPlus 自定義.vm模板的生成

    為更加快捷方便的開發(fā)代碼,使用MybatisPlus的代碼自動(dòng)生成功能,將一些繁瑣的操作自動(dòng)生成,本文主要介紹了MybatisPlus 自定義.vm模板的生成,感興趣的可以了解一下
    2024-03-03
  • 淺談java多線程編程

    淺談java多線程編程

    這篇文章主要介紹了java多線程編程的相關(guān)資料,文中講解非常細(xì)致,幫助大家更好的理解和學(xué)習(xí)java多線程,感興趣的朋友可以了解下
    2020-08-08
  • java序列化的種類和使用場景詳解

    java序列化的種類和使用場景詳解

    本文詳細(xì)介紹了序列化的概念、Java內(nèi)置序列化、自定義序列化、第三方序列化框架(如Kryo、Protobuf)以及在分布式系統(tǒng)和RPC框架中的應(yīng)用,通過比較不同序列化方式的優(yōu)缺點(diǎn),指導(dǎo)開發(fā)者選擇合適的序列化方案,以確保系統(tǒng)的性能、安全性和可維護(hù)性
    2025-01-01
  • Java網(wǎng)絡(luò)編程基礎(chǔ)教程之Socket入門實(shí)例

    Java網(wǎng)絡(luò)編程基礎(chǔ)教程之Socket入門實(shí)例

    這篇文章主要介紹了Java網(wǎng)絡(luò)編程基礎(chǔ)教程之Socket入門實(shí)例,本文講解了創(chuàng)建Socket、Socket發(fā)送數(shù)據(jù)、Socket讀取數(shù)據(jù)、關(guān)閉Socket等內(nèi)容,都是最基礎(chǔ)的知識點(diǎn),需要的朋友可以參考下
    2014-09-09
  • kafka?消息隊(duì)列中點(diǎn)對點(diǎn)與發(fā)布訂閱的區(qū)別說明

    kafka?消息隊(duì)列中點(diǎn)對點(diǎn)與發(fā)布訂閱的區(qū)別說明

    這篇文章主要介紹了kafka?消息隊(duì)列中點(diǎn)對點(diǎn)與發(fā)布訂閱的區(qū)別說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • springBoot 過濾器去除請求參數(shù)前后空格實(shí)例詳解

    springBoot 過濾器去除請求參數(shù)前后空格實(shí)例詳解

    這篇文章主要為大家介紹了springBoot 過濾器去除請求參數(shù)前后空格實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • springboot中@Value的工作原理說明

    springboot中@Value的工作原理說明

    這篇文章主要介紹了springboot中@Value的工作原理,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Spring Cloud Config 使用本地配置文件方式

    Spring Cloud Config 使用本地配置文件方式

    這篇文章主要介紹了Spring Cloud Config 使用本地配置文件方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • springboot配置flyway(入門級別教程)

    springboot配置flyway(入門級別教程)

    本文介紹了springboot配置flyway,主要介紹基于SpringBoot集成flyway來管理數(shù)據(jù)庫的變更,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-09-09
  • Java實(shí)現(xiàn)數(shù)組轉(zhuǎn)字符串及字符串轉(zhuǎn)數(shù)組的方法分析

    Java實(shí)現(xiàn)數(shù)組轉(zhuǎn)字符串及字符串轉(zhuǎn)數(shù)組的方法分析

    這篇文章主要介紹了Java實(shí)現(xiàn)數(shù)組轉(zhuǎn)字符串及字符串轉(zhuǎn)數(shù)組的方法,結(jié)合實(shí)例形式分析了Java字符串及數(shù)組相關(guān)的分割、遍歷、追加等操作技巧,需要的朋友可以參考下
    2018-06-06

最新評論

丽水市| 文水县| 曲水县| 宁阳县| 钟祥市| 册亨县| 富阳市| 四川省| 桐庐县| 正镶白旗| 垣曲县| 绵竹市| 衡阳县| 新源县| 梨树县| 左权县| 托克逊县| 双柏县| 民乐县| 政和县| 图片| 平潭县| 曲阜市| 罗甸县| 邵阳县| 双峰县| 远安县| 馆陶县| 永登县| 陆良县| 民丰县| 泾源县| 西青区| 若尔盖县| 德庆县| 吐鲁番市| 旺苍县| 鸡泽县| 晋城| 镇坪县| 枣强县|