欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java从数据库中读取Blob对象图片并显示的方法

程序员文章站 2024-03-01 18:19:46
本文实例讲述了java从数据库中读取blob对象图片并显示的方法。分享给大家供大家参考。具体实现方法如下: 第一种方法: 大致方法就是,从数据库中读出blob的流来,写...

本文实例讲述了java从数据库中读取blob对象图片并显示的方法。分享给大家供大家参考。具体实现方法如下:

第一种方法:

大致方法就是,从数据库中读出blob的流来,写到页面中去:

复制代码 代码如下:
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();
}

 
在页面中:
复制代码 代码如下:
<%
string path = request.getcontextpath();
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>
 
<img name="pic" src="<%=basepath+"servlet/downloadasstream"%>"/>

 
搞定。

第二种方法:

整个流程分为四步,连接oracle数据库 -> 读取blob图片字段 -> 对图片进行缩放 ->把图片展示在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;
  
    private string stridname;
 
    private string strimgname;
  
    public oraclequerybean(){
        try{
            class.forname(oracledrivername);
        }catch(classnotfoundexception ex){
            system.out.println("加载jdbc驱动失败,原因:" + ex.getmessage());
        }
    }
  
    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类中增加一个函数,来进行读取,具体代码如下:

复制代码 代码如下:
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类中增加一个函数,来进行缩放,具体代码如下:

复制代码 代码如下:
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;
  
    private string stridname;
  
    private string strimgname;
  
    public oraclequerybean(){
        try{
            class.forname(oracledrivername);
        }catch(classnotfoundexception ex){
            system.out.println("加载jdbc驱动失败,原因:" + ex.getmessage());
        }
    }
  
    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;
    }
  
    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;
    }

    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;
    }

    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;
    }
}

下面是我的存储读取blob图片的案例

复制代码 代码如下:
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();  
    } 
}

复制代码 代码如下:
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显示

复制代码 代码如下:
<img style="width:320px;height:240px" src="<%=basepath%>/genimage?id=3"/>

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>

希望本文所述对大家的java程序设计有所帮助。