学者谷

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

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

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

第一种方法:

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

复制代码 代码如下:Connection conn = onnection();

String sql = "SELECT picture FROM teacher WHERE id=1";

PreparedStatement ps = null;

ResultSet rs = null;

InputStream is = null;

OutputStream os = null;

try {

ps = areStatement(sql);

rs = uteQuery();

if(()){

is = inaryStream(1);

}

ontentType("text/html");

os = utputStream();

int num;

byte buf[] = new byte[1024];

while( (num=(buf))!=-1 ){

e(buf, 0, num);

}

} catch (SQLException e) {

tStackTrace();

}

try {

e();

e();

e();

e();

} catch (SQLException e) {

tStackTrace();

}

在页面中:

复制代码 代码如下:<%

String path = ontextPath();

String basePath = cheme()+"://"+erverName()+":"+erverPort()+path+"/";

%>

搞定。

第二种方法:

整个流程分为四步,连接oracle数据库 -> 读取blob图片字段 -> 对图片进行缩放 ->把图片展示在jsp页面上。

复制代码 代码如下:import .*;

import .*;

import eIO;

import eredImage;

import neTransformOp;

import neTransform;

public class OracleQueryBean {

private final String oracleDriverName = "leDriver";

private Connection myConnection = null;

private String strTabName;

private String strIDName;

private String strImgName;

public OracleQueryBean(){

try{

ame(oracleDriverName);

}catch(ClassNotFoundException ex){

tln("加载jdbc驱动失败,原因:" + essage());

}

}

public Connection getConnection(){

try{

//用户名+密码; 以下使用的Test就是Oracle里的表空间

//从配置文件中读取数据库信息

GetPara oGetPara = new GetPara();

String strIP = ara("serverip");

String strPort = ara("port");

String strDBName = ara("dbname");

String strUser = ara("user");

String strPassword = ara("password");

abName = ara("tablename");

DName = ara("imgidname");

mgName = ara("imgname");

String oracleUrlToConnect ="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName;

nnection = onnection(oracleUrlToConnect, strUser, strPassword);

}catch(Exception ex){

tln("Can not get connection:" + essage());

tln("请检测配置文件中的.数据库信息是否正确." );

}

return nnection;

}

}

2. 读取blob字段

在OracleQueryBean类中增加一个函数,来进行读取,具体代码如下:

复制代码 代码如下:public byte[] GetImgByteById(String strID, int w, int h){

//tln("Get img data which id is " + nID);

if(myConnection == null)

onnection();

byte[] data = null;

try {

Statement stmt = teStatement();

ResultSet myResultSet = uteQuery("select " + DName + " from " + abName + " where " + DName + "=" + strID);

StringBuffer myStringBuffer = new StringBuffer();

if (()) {

blob = lob(mgName);

InputStream inStream = inaryStream();

try {

long nLen = th();

int nSize = (int) nLen;

//tln("img data size is :" + nSize);

data = new byte[nSize];

(data);

e();

} catch (IOException e) {

tln("获取图片数据失败,原因:" + essage());

}

data = ChangeImgSize(data, w, h);

}

tln(ring());

it();

e();

} catch (SQLException ex) {

tln(essage());

}

return data;

}

3. 缩放图片

因为图片的大小可能不一致,但是在页面中输出的大小需要统一,所以需要

在OracleQueryBean类中增加一个函数,来进行缩放,具体代码如下:

复制代码 代码如下:private byte[] ChangeImgSize(byte[] data, int nw, int nh){

byte[] newdata = null;

try{

BufferedImage bis = (new ByteArrayInputStream(data));

int w = idth();

int h = eight();

double sx = (double) nw / w;

double sy = (double) nh / h;

AffineTransform transform = new AffineTransform();

oScale(sx, sy);

AffineTransformOp ato = new AffineTransformOp(transform, null);

//原始颜色

BufferedImage bid = new BufferedImage(nw, nh, _3BYTE_BGR);

er(bis, bid);

//转换成byte字节

ByteArrayOutputStream baos = new ByteArrayOutputStream();

e(bid, "jpeg", baos);

newdata = teArray();

}catch(IOException e){

tStackTrace();

}

return newdata;

}

4. 展示在页面

页面使用OracleQueryBean来根据用户提供的图片id进行查询,在读取并进行缩放后,通过jsp页面进行展示,具体代码如下:

复制代码 代码如下:<%@ page="" language="java" contenttype="text/html;;charset=gbk">

<%

response.setContentType("image/jpeg");

//图片在数据库中的 ID

String strID = arameter("id");

//要缩略或放大图片的宽度

String strWidth = arameter("w");

//要缩略或放大图片的高度

String strHeight = arameter("h");

byte[] data = null;

if(strID != null){

int nWith = eInt(strWidth);

int nHeight = eInt(strHeight);

//获取图片的byte数据

data = mgByteById(strID, nWith, nHeight);

ServletOutputStream op = utputStream();

e(data, 0, th);

e();

op = null;

hBuffer();

//清除输出流,防止释放时被捕获异常

r();

out = Body();

}

%>

5. OracleQueryBean查询类的整体代码

文件代码如下所示:

复制代码 代码如下:import .*;

import .*;

import eIO;

import eredImage;

import neTransformOp;

import neTransform;

public class OracleQueryBean {

private final String oracleDriverName = "leDriver";

private Connection myConnection = null;

private String strTabName;

private String strIDName;

private String strImgName;

public OracleQueryBean(){

try{

ame(oracleDriverName);

}catch(ClassNotFoundException ex){

tln("加载jdbc驱动失败,原因:" + essage());

}

}

public Connection getConnection(){

try{

//用户名+密码; 以下使用的Test就是Oracle里的表空间

//从配置文件中读取数据库信息

GetPara oGetPara = new GetPara();

String strIP = ara("serverip");

String strPort = ara("port");

String strDBName = ara("dbname");

String strUser = ara("user");

String strPassword = ara("password");

abName = ara("tablename");

DName = ara("imgidname");

mgName = ara("imgname");

String oracleUrlToConnect ="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName;

nnection = onnection(oracleUrlToConnect, strUser, strPassword);

}catch(Exception ex){

tln("Can not get connection:" + essage());

tln("请检测配置文件中的数据库信息是否正确." );

}

return nnection;

}

public byte[] GetImgByteById(String strID, int w, int h){

//tln("Get img data which id is " + nID);

if(myConnection == null)

onnection();

byte[] data = null;

try {

Statement stmt = teStatement();

ResultSet myResultSet = uteQuery("select " + DName + " from " + abName + " where " + DName + "=" + strID);

StringBuffer myStringBuffer = new StringBuffer();

if (()) {

blob = lob(mgName);

InputStream inStream = inaryStream();

try {

long nLen = th();

int nSize = (int) nLen;

//tln("img data size is :" + nSize);

data = new byte[nSize];

(data);

e();

} catch (IOException e) {

tln("获取图片数据失败,原因:" + essage());

}

data = ChangeImgSize(data, w, h);

}

tln(ring());

it();

e();

} catch (SQLException ex) {

tln(essage());

}

return data;

}

public byte[] GetImgByteById(String strID){

//tln("Get img data which id is " + nID);

if(myConnection == null)

onnection();

byte[] data = null;

try {

Statement stmt = teStatement();

ResultSet myResultSet = uteQuery("select " + DName + " from " + abName + " where " + DName + "=" + strID);

StringBuffer myStringBuffer = new StringBuffer();

if (()) {

blob = lob(mgName);

InputStream inStream = inaryStream();

try {

long nLen = th();

int nSize = (int) nLen;

data = new byte[nSize];

(data);

e();

} catch (IOException e) {

tln("获取图片数据失败,原因:" + essage());

}

}

tln(ring());

it();

e();

} catch (SQLException ex) {

tln(essage());

}

return data;

}

private byte[] ChangeImgSize(byte[] data, int nw, int nh){

byte[] newdata = null;

try{

BufferedImage bis = (new ByteArrayInputStream(data));

int w = idth();

int h = eight();

double sx = (double) nw / w;

double sy = (double) nh / h;

AffineTransform transform = new AffineTransform();

oScale(sx, sy);

AffineTransformOp ato = new AffineTransformOp(transform, null);

//原始颜色

BufferedImage bid = new BufferedImage(nw, nh, _3BYTE_BGR);

er(bis, bid);

//转换成byte字节

ByteArrayOutputStream baos = new ByteArrayOutputStream();

e(bid, "jpeg", baos);

newdata = teArray();

}catch(IOException e){

tStackTrace();

}

return newdata;

}

}

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

复制代码 代码如下:import .*;

import .*;

public class InsertPhoto {

public static void main(String[] args) throws Exception{

ame("er");

Connection con = onnection("jdbc:mysql://);

File f = new File("e:/123.jpg");

FileInputStream fis = new FileInputStream(f);

String sql = " into photo(photo,photoName) values(";

PreparedStatement pstmt = areStatement(sql);

inaryStream(1,fis,(int)th());

tring(2, "测试图片");

uteUpdate();

e();

e();

e();

}

}

复制代码 代码如下:import eredImage;

import eredInputStream;

import ception;

import tStream;

import utStream;

import ection;

import erManager;

import ltSet;

import xception;

import ement;

import eIO;

import Servlet;

import ServletRequest;

import ServletResponse;

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(arameter("id") != null){

response.setContentType("image/jpeg");

try {

InputStream is = query_getPhotoImageBlob(eInt(arameter("id"))) ;

if(is != null){

is = new BufferedInputStream(is) ;

BufferedImage bi = (is) ;

OutputStream os = utputStream() ;

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os) ;

de(bi);

e();

e();

}

} catch(IOException e){

tStackTrace();

}catch (NumberFormatException e) {

// TODO Auto-generated catch block

tStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

tStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

tStackTrace();

}

}

}

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 {

ame("er");

con = onnection("jdbc:mysql://);

stmt = teStatement();

rs = uteQuery(sql);

if (())

result = lob("photo")inaryStream();

} catch (SQLException e) {

// TODO: handle exception

tln(essage());

}finally{

e();

e();

e();

}

return result;

}

}

jsp显示

复制代码 代码如下:

中配置

复制代码 代码如下:

genImage

ReadPhoto

genImage

/genImage

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