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

本文介绍两种从Oracle数据库读取Blob类型图片的方法:直接显示图片流及读取后进行缩放再显示。涉及数据库连接、Blob对象处理及图片缩放等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从数据库中读取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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值