`
ynztpwl
  • 浏览: 55519 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

从数据库中读取Blob对象图片并显示

 
阅读更多

从数据库中读取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"%>"/>

搞定。

来源:(http://blog.sina.com.cn/s/blog_556c72d20100ejtw.html) - JAVA读取Oracle中的blob图片字段并显示_〓帅_新浪博客第二种方法:

整个流程分为四步,连接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;

}

}

分享到:
评论

相关推荐

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

    主要介绍了Java从数据库中读取Blob对象图片并显示的方法,实例分析了Java读取数据库中Blob对象图片的技巧与操作方法,需要的朋友可以参考下

    使用PLSQL从数据库中读取BLOB对象

    使用PLSQL从数据库中读取BLOB对象

    vc+odbc+access如何对数据库中的位图读取和存入

    大对象文档以二进制数据形式保存在BLOB类型的字段中,这些大对象可能是Word、Execl或图片文件等,目前多数数据库都支持BLOB类型的字段。 VC存取这些大对象数据有众多方法,如OLE、ActiveX等,事实上VC的MFC提供了一...

    数据库中文件夹的整体存储与随机访问

    当前的数据库系统不能提供对文件夹存取的直接支持。针对该问题,综合数据库二...从目录结构对象中可选择欲访问的文件,确定其在文件数据BLOB 中的位置和大小,读取其对应的数据, 从而实现对数据库中文件夹的随机访问。

    Oracle中Blob字段的写入处理

    此文档是对于oracle数据库中blob类型字段二进制大对象的读取和解析

    数据库学习之blob类型的数据操作

    目录 blob类型简介 BLOB操作相关API介绍 编程示例  运行结果 由于近期做Linux的项目涉及到字节流的数据库存储和读取的sqlite3与C语言的相关函数...在计算机中,BLOB常常是数据库中用来存储二进制文件的字段类型。常

    利用Blob进行文件上传的完整步骤

    Blob对象指的是字节序列,并且具有size属性,是字节序列中的字节总数,和一个type属性,它是小写的ASCII编码的字符串表示的媒体类型字节序列。 size:以字节数返回字节序列的大小。获取时,符合要求的用户代理必须...

    Oracle BLOB,BFILE大文件存储和FTP传输文件

    数据库为Oracle 10g,代码为Visual Studio 2008 VC++开发,软件中的代码有BLOB存储和读取,BFILE存储与读取,FTP上传与下载,以及数据库数据的添加与删除功能。程序已经将数据库的IP,用户名,密码去掉,使用的童鞋把...

    深入浅析mybatis oracle BLOB类型字段保存与读取

     BLOB是指二进制大对象也就是英文Binary Large Object的所写,而CLOB是指大字符对象也就是英文Character Large Object的所写。其中BLOB是用来存储大量二进制数据的;CLOB用来存储大量文本数据。BLOB通常用来保存...

    PB9 操作updateblob selectblob 对象

    PB大文本数据(文件)写入到数据库,从数据库中读取并打开 代码已封装为不可视类

    鲸鲨云国产可视化数据库迁移工具DBPorterPlus免费版1.2

    完全国产自主知识产权的数据库迁移工具:鲸鲨云DBPorterPLus。...功能齐全:全库迁移,支持数据表、视图、约束、序列,支持大对象(Blob,Clob),支持导出DDL。 性能优异:实时传输,直连数据库,批量读取和插入。

    VC++使用ADO实现BLOB二进制大对象数据的存取

    内容索引:VC/C++源码,数据库应用,二进制,BLOB 在vc++开发过程中,有时候需要将数据以二进制方式存储在数据库中,本代码就是实现这一过程的示例,VC++使用ADO实现BLOB二进制大对象数据的存取,其存取的方式与普通...

    python3图片转换二进制存入mysql

    复制代码 代码如下:# -*- coding: UTF-8 -*-import MySQLdb as mdbimport systry: #用读文件模式打开图片 fin = open(“../web.jpg”) #将文本读入img对象中 img = fin.read() #关闭文件 fin.close()except I

    Python Cookbook

    9.1 同步对象中的所有方法 339 9.2 终止线程 342 9.3 将Queue.Queue用作优先级队列 344 9.4 使用线程池 346 9.5 以多组参数并行执行函数 349 9.6 用简单的消息传递协调线程 351 9.7 储存线程信息 353 9.8 无...

    adodb_tools:Adodb_tools 允许通过 ADO OLEDB 组件与不同类型的数据库进行通信。-matlab开发

    包 adodb_toolbox 允许通过 Microsoft 的 ADO... 支持读取和写入 BLOB 对象。 这个包可以被研究、修改、定制、重写和在其他包中使用,没有任何限制。 包含并记录了所有代码。 软件是根据BSD许可(随附)分发的。

    ado[1].net中文手册 学习 ado.net的重要资料

    从数据库中获取 BLOB 值:描述如何使用 DataReader 从数据库中返回二进制大对象 (BLOB)。 执行数据库操作和修改数据:描述如何使用 Command 对数据源发出 INSERT、UPDATE 和 DELETE 命令,以及如何执行目录操作(如...

    IdentityCache是​​可插入ActiveRecord的Blob级缓存解决方案。 不要#寻找,#获取!-Ruby开发

    IdentityCache使您可以指定如何在模型级别上缓存模型对象,并在生产中使用的ActiveRecord缓存读取和从Shopify提取的过程中增加了许多IdentityCache Opt便利。 IdentityCache使您可以指定在模型级别上如何缓存模型...

    java jdk实列宝典 光盘源代码

    读写Blob数据,blob数据常以二进制形式存储比较大的文件数据,如图片、视频文件等,本文介绍如何往数据库中读写blob数据,BlobData.java; 使用ResultSet更新数据库,UpdateWithResultSet.java; 使用RowSet,....

    JS实现图片预览的两种方式

    那么要实现预览有两种方式:一种是用window.URL.createObjectURl方法对选择的图片数据(可以勉强理解为input的value)生成一个blob对象路径,第二种是用获取 FileReader读取器。 那么无论那种方法,首先都得得到文件...

Global site tag (gtag.js) - Google Analytics