在OracleQueryBean类中增加一个函数,来进行读取,具体代码如下:
/**
* 根据图片在数据库中的ID进行读取
* @param strID 图片字段ID
* @param w 需要缩到的宽度
* @param h 需要缩到高度
* @return
*/
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;
}
页面使用OracleQueryBean来根据用户提供的图片id进行查询,在读取并进行缩放后,通过jsp页面进行展示,具体代码如下:
<%@ page language="java" contentType="text/html;;charset=gbk" %>
<%
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();
}
%>
在下载图片之前,查询数据库中所有图片的主键。在前台遍历返回结果并用js动态生成img标签。