Java从数据库中读取Blob对象图片并显示的方法
本文实例讲述了Java从数据库中读取Blob对象图片并显示的方法。分享给大家供大家参考。具体实现方法如下:
第一种方法:
大致方法就是,从数据库中读出Blob的流来,写到页面中去:
Connectionconn=DBManager.getConnection(); Stringsql="SELECTpictureFROMteacherWHEREid=1"; PreparedStatementps=null; ResultSetrs=null; InputStreamis=null; OutputStreamos=null; try{ ps=conn.prepareStatement(sql); rs=ps.executeQuery(); if(rs.next()){ is=rs.getBinaryStream(1); } response.setContentType("text/html"); os=response.getOutputStream(); intnum; bytebuf[]=newbyte[1024]; while( (num=is.read(buf))!=-1 ){ os.write(buf,0,num); } }catch(SQLExceptione){ e.printStackTrace(); } try{ is.close(); os.close(); rs.close(); ps.close(); }catch(SQLExceptione){ e.printStackTrace(); }
在页面中:
<% Stringpath=request.getContextPath(); StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <imgname="pic"src="<%=basePath+"servlet/DownloadAsStream"%>"/>
搞定。
第二种方法:
整个流程分为四步,连接oracle数据库->读取blob图片字段->对图片进行缩放->把图片展示在jsp页面上。
importjava.sql.*; importjava.io.*; importjavax.imageio.ImageIO; importjava.awt.image.BufferedImage; importjava.awt.image.AffineTransformOp; importjava.awt.geom.AffineTransform; publicclassOracleQueryBean{ privatefinalStringoracleDriverName="oracle.jdbc.driver.OracleDriver"; privateConnectionmyConnection=null; privateStringstrTabName; privateStringstrIDName; privateStringstrImgName; publicOracleQueryBean(){ try{ Class.forName(oracleDriverName); }catch(ClassNotFoundExceptionex){ System.out.println("加载jdbc驱动失败,原因:"+ex.getMessage()); } } publicConnectiongetConnection(){ try{ //用户名+密码;以下使用的Test就是Oracle里的表空间 //从配置文件中读取数据库信息 GetParaoGetPara=newGetPara(); StringstrIP=oGetPara.getPara("serverip"); StringstrPort=oGetPara.getPara("port"); StringstrDBName=oGetPara.getPara("dbname"); StringstrUser=oGetPara.getPara("user"); StringstrPassword=oGetPara.getPara("password"); this.strTabName=oGetPara.getPara("tablename"); this.strIDName=oGetPara.getPara("imgidname"); this.strImgName=oGetPara.getPara("imgname"); StringoracleUrlToConnect="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName; this.myConnection=DriverManager.getConnection(oracleUrlToConnect,strUser,strPassword); }catch(Exceptionex){ System.out.println("Cannotgetconnection:"+ex.getMessage()); System.out.println("请检测配置文件中的数据库信息是否正确."); } returnthis.myConnection; } }
2.读取blob字段
在OracleQueryBean类中增加一个函数,来进行读取,具体代码如下:
publicbyte[]GetImgByteById(StringstrID,intw,inth){ //System.out.println("Getimgdatawhichidis"+nID); if(myConnection==null) this.getConnection(); byte[]data=null; try{ Statementstmt=myConnection.createStatement(); ResultSetmyResultSet=stmt.executeQuery("select"+this.strIDName+"from"+this.strTabName+"where"+this.strIDName+"="+strID); StringBuffermyStringBuffer=newStringBuffer(); if(myResultSet.next()){ java.sql.Blobblob=myResultSet.getBlob(this.strImgName); InputStreaminStream=blob.getBinaryStream(); try{ longnLen=blob.length(); intnSize=(int)nLen; //System.out.println("imgdatasizeis:"+nSize); data=newbyte[nSize]; inStream.read(data); inStream.close(); }catch(IOExceptione){ System.out.println("获取图片数据失败,原因:"+e.getMessage()); } data=ChangeImgSize(data,w,h); } System.out.println(myStringBuffer.toString()); myConnection.commit(); myConnection.close(); }catch(SQLExceptionex){ System.out.println(ex.getMessage()); } returndata; }
3.缩放图片
因为图片的大小可能不一致,但是在页面中输出的大小需要统一,所以需要
在OracleQueryBean类中增加一个函数,来进行缩放,具体代码如下:
privatebyte[]ChangeImgSize(byte[]data,intnw,intnh){ byte[]newdata=null; try{ BufferedImagebis=ImageIO.read(newByteArrayInputStream(data)); intw=bis.getWidth(); inth=bis.getHeight(); doublesx=(double)nw/w; doublesy=(double)nh/h; AffineTransformtransform=newAffineTransform(); transform.setToScale(sx,sy); AffineTransformOpato=newAffineTransformOp(transform,null); //原始颜色 BufferedImagebid=newBufferedImage(nw,nh,BufferedImage.TYPE_3BYTE_BGR); ato.filter(bis,bid); //转换成byte字节 ByteArrayOutputStreambaos=newByteArrayOutputStream(); ImageIO.write(bid,"jpeg",baos); newdata=baos.toByteArray(); }catch(IOExceptione){ e.printStackTrace(); } returnnewdata; }
4.展示在页面
页面使用OracleQueryBean来根据用户提供的图片id进行查询,在读取并进行缩放后,通过jsp页面进行展示,具体代码如下:
<%@pagelanguage="java"contentType="text/html;;charset=gbk"%> <jsp:useBeanid="OrcleQuery"scope="page"class="HLFtiDemo.OracleQueryBean"/> <% response.setContentType("image/jpeg"); //图片在数据库中的ID StringstrID=request.getParameter("id"); //要缩略或放大图片的宽度 StringstrWidth=request.getParameter("w"); //要缩略或放大图片的高度 StringstrHeight=request.getParameter("h"); byte[]data=null; if(strID!=null){ intnWith=Integer.parseInt(strWidth); intnHeight=Integer.parseInt(strHeight); //获取图片的byte数据 data=OrcleQuery.GetImgByteById(strID,nWith,nHeight); ServletOutputStreamop=response.getOutputStream(); op.write(data,0,data.length); op.close(); op=null; response.flushBuffer(); //清除输出流,防止释放时被捕获异常 out.clear(); out=pageContext.pushBody(); } %>
5.OracleQueryBean查询类的整体代码
OracleQueryBean.java文件代码如下所示:
importjava.sql.*; importjava.io.*; importjavax.imageio.ImageIO; importjava.awt.image.BufferedImage; importjava.awt.image.AffineTransformOp; importjava.awt.geom.AffineTransform; publicclassOracleQueryBean{ privatefinalStringoracleDriverName="oracle.jdbc.driver.OracleDriver"; privateConnectionmyConnection=null; privateStringstrTabName; privateStringstrIDName; privateStringstrImgName; publicOracleQueryBean(){ try{ Class.forName(oracleDriverName); }catch(ClassNotFoundExceptionex){ System.out.println("加载jdbc驱动失败,原因:"+ex.getMessage()); } } publicConnectiongetConnection(){ try{ //用户名+密码;以下使用的Test就是Oracle里的表空间 //从配置文件中读取数据库信息 GetParaoGetPara=newGetPara(); StringstrIP=oGetPara.getPara("serverip"); StringstrPort=oGetPara.getPara("port"); StringstrDBName=oGetPara.getPara("dbname"); StringstrUser=oGetPara.getPara("user"); StringstrPassword=oGetPara.getPara("password"); this.strTabName=oGetPara.getPara("tablename"); this.strIDName=oGetPara.getPara("imgidname"); this.strImgName=oGetPara.getPara("imgname"); StringoracleUrlToConnect="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName; this.myConnection=DriverManager.getConnection(oracleUrlToConnect,strUser,strPassword); }catch(Exceptionex){ System.out.println("Cannotgetconnection:"+ex.getMessage()); System.out.println("请检测配置文件中的数据库信息是否正确."); } returnthis.myConnection; } publicbyte[]GetImgByteById(StringstrID,intw,inth){ //System.out.println("Getimgdatawhichidis"+nID); if(myConnection==null) this.getConnection(); byte[]data=null; try{ Statementstmt=myConnection.createStatement(); ResultSetmyResultSet=stmt.executeQuery("select"+this.strIDName+"from"+this.strTabName+"where"+this.strIDName+"="+strID); StringBuffermyStringBuffer=newStringBuffer(); if(myResultSet.next()){ java.sql.Blobblob=myResultSet.getBlob(this.strImgName); InputStreaminStream=blob.getBinaryStream(); try{ longnLen=blob.length(); intnSize=(int)nLen; //System.out.println("imgdatasizeis:"+nSize); data=newbyte[nSize]; inStream.read(data); inStream.close(); }catch(IOExceptione){ System.out.println("获取图片数据失败,原因:"+e.getMessage()); } data=ChangeImgSize(data,w,h); } System.out.println(myStringBuffer.toString()); myConnection.commit(); myConnection.close(); }catch(SQLExceptionex){ System.out.println(ex.getMessage()); } returndata; }
publicbyte[]GetImgByteById(StringstrID){ //System.out.println("Getimgdatawhichidis"+nID); if(myConnection==null) this.getConnection(); byte[]data=null; try{ Statementstmt=myConnection.createStatement(); ResultSetmyResultSet=stmt.executeQuery("select"+this.strIDName+"from"+this.strTabName+"where"+this.strIDName+"="+strID); StringBuffermyStringBuffer=newStringBuffer(); if(myResultSet.next()){ java.sql.Blobblob=myResultSet.getBlob(this.strImgName); InputStreaminStream=blob.getBinaryStream(); try{ longnLen=blob.length(); intnSize=(int)nLen; data=newbyte[nSize]; inStream.read(data); inStream.close(); }catch(IOExceptione){ System.out.println("获取图片数据失败,原因:"+e.getMessage()); } } System.out.println(myStringBuffer.toString()); myConnection.commit(); myConnection.close(); }catch(SQLExceptionex){ System.out.println(ex.getMessage()); } returndata; }
privatebyte[]ChangeImgSize(byte[]data,intnw,intnh){ byte[]newdata=null; try{ BufferedImagebis=ImageIO.read(newByteArrayInputStream(data)); intw=bis.getWidth(); inth=bis.getHeight(); doublesx=(double)nw/w; doublesy=(double)nh/h; AffineTransformtransform=newAffineTransform(); transform.setToScale(sx,sy); AffineTransformOpato=newAffineTransformOp(transform,null); //原始颜色 BufferedImagebid=newBufferedImage(nw,nh,BufferedImage.TYPE_3BYTE_BGR); ato.filter(bis,bid); //转换成byte字节 ByteArrayOutputStreambaos=newByteArrayOutputStream(); ImageIO.write(bid,"jpeg",baos); newdata=baos.toByteArray(); }catch(IOExceptione){ e.printStackTrace(); } returnnewdata; } }