我的要求是通过jsp将艺术家详细信息和他的图片插入到oracle数据库中,并通过另一个jsp程序检索信息和图片。
艺术家表有五列,四列是varchar2,第五列是blob类型。
我已成功插入并成功检索但问题只显示图像。下面是代码。我被卡住了。我需要帮助。请建议我。
PreparedStatement ps=con.prepareStatement("select * from artist");
ResultSet rs=ps.executeQuery();
while(rs.next()){ %>
<table><tr><th>artist fast name:</th><td><%=rs.getString(1) %></td></tr>
<tr><th>artist middle name:</th><td><%=rs.getString(2) %></td></tr>
<tr><th>artist last name</th><td><%=rs.getString(3) %></td></tr>
<tr><th>artist job</th><td><%=rs.getString(4) %></td></tr>
<tr><th>artist image</th><td><img src="
<%
Blob bl=rs.getBlob(5);
byte[] image=bl.getBytes(1, (int)bl.length());
response.setContentType("image/jpeg");
OutputStream o = response.getOutputStream();
o.write(image);
o.flush();
o.close();
}
%>" height="100" width="100" alt="bye"/> </td></tr>
</table>
<%
con.close();
答案 0 :(得分:1)
从版本6开始,Java SE提供了JAXB, bytes 可以通过它转换为 base64 string 。您也可以在此处将图像byte[]
转换为 base 64 string ,然后使用<img
html 标记将其指定为src数据作为基础64即src="data:image/png;base64,
。
修改您的代码,如下所示:
<%
PreparedStatement ps=con.prepareStatement("select * from artist");
ResultSet rs=ps.executeQuery();
while(rs.next()){ %>
<table><tr><th>artist fast name:</th><td><%=rs.getString(1) %></td></tr>
<tr><th>artist middle name:</th><td><%=rs.getString(2) %></td></tr>
<tr><th>artist last name</th><td><%=rs.getString(3) %></td></tr>
<tr><th>artist job</th><td><%=rs.getString(4) %></td></tr>
<tr><th>artist image</th><td>
<%
Blob bl=rs.getBlob(5);
byte[] image=bl.getBytes(1, (int)bl.length());
%>
<img src="data:image/jpeg;base64, <%=javax.xml.bind.DatatypeConverter.printBase64Binary(image)%>
" height="100" width="100" alt="bye"/> </td></tr>
</table>
<%
}
con.close();
%>
这是另一个示例 jsp 页面,用于获得清晰的想法:
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.io.*"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
BufferedImage bImage = ImageIO.read(new File("/home/visruth/Desktop/Visruth.jpg"));//give the path of an image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bImage, "jpg", baos );
baos.flush();
byte[] imageInByteArray = baos.toByteArray();
baos.close();
String b64 = javax.xml.bind.DatatypeConverter.printBase64Binary(imageInByteArray);
%>
<div>
<p>As of v6, Java SE provides JAXB</p>
<img src="data:image/jpg;base64, <%=b64%>" alt="Visruth.jpg not found" />
</div>
</body>
</html>