當前位置:學問谷 >

行業範例 >數據庫操作系統 >

講解Java從數據庫中讀取Blob對象圖片並顯示的方法

講解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程序設計有所幫助。

  • 文章版權屬於文章作者所有,轉載請註明 https://xuewengu.com/flhy/shujuku/geqyg.html