講解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顯示
複製代碼 代碼如下:
中配置
複製代碼 代碼如下:
希望本文所述對大家的Java程序設計有所幫助。
-
可視門禁系統接線圖解
隨着感應卡技術,生物識別技術的發展,門禁系統得到了飛躍式的發展。以下是小編為大家精心整理的可視門禁系統接線圖解,歡迎大家閲讀。一、設備安裝(1)前端設備A、進門處安裝讀卡器。在讀卡器感應範圍內,切勿靠近或接觸高頻或強磁場(如重載馬達、監視器等),並需配合...
-
錄入數據庫的記錄説課稿
一、説教材《錄入數據庫的記錄》這一課是海南出版社義務教育九年級教材《信息技術》的第二課,這一課用時一個課時。它是學生學習數據庫軟件Access的基礎,也是形成學生“瞭解熟悉——基本技能——綜合運用”這一合理知識鏈的必要環節。是第一章《用數據庫來管理信...
-
數據庫技術信息的管理論文
一、信息管理中計算機數據庫技術的運用建議(一)增強數據的完整性。在數據庫運行過程中,最基本的要求就是數據的完整、準確。數據是數據庫的主要內容,數據的完整是保證數據庫順利運行的基礎條件,用户在編制信息時候儘量編輯完整信息,這樣數據庫才有更高的價值,信息管理...
-
服務質量管理系統論文
服務質量(ServiceQuality)是指服務能夠滿足規定和潛在需求的特徵和特性的總和,是指服務工作能夠滿足被服務者需求的程度。下面是小編為你帶來的服務質量管理系統論文,歡迎閲讀。服務質量管理系統及其應用摘要:隨着電信市場的不斷擴大,各大運營商所面臨的機遇與挑戰...
相關文章
- 利用Zabbix監控數據庫系統方法介紹
- vocabulary是什麼意思 vocabulary中文釋義-短語-例句
- win10系統第一次打開acrobat不顯示菜單欄和工具欄解決方法
- Java數據庫編程中的幾個常用技巧
- 使用Java程序連接各種數據庫的方法
- blackboard是什麼意思 blackboard釋義-詞組-例句
- Java連接MYSQL數據庫的具體步驟
- 機器學習和數據挖掘的就業前景如何,實現的話一般用C++還是python,比較擅長java和objc,準ruby程序員
- Jason Mraz & Colbie Caillat的Lucky樂評
- football是什麼意思-如何解釋football的意思