从Oracle中读取blob类型存储的图片

最近做个项目使用S2SH和Oracle数据库,其中photo表使用blob类型存储的图片。在网上搜了很多资料,现在把实例代码发一下。
Photo实体类

public class Photo implements java.io.Serializable {

// Fields

private Integer id;
private Album album;
private Date createtime;
private String name;
private String contentType;
private Blob thumbnail;
private Blob content;
private Integer orderid;
private Set facelookmarks = new HashSet(0);
private Set facelookactivities = new HashSet(0);
private Set facelookcomments = new HashSet(0);
/*setter,getter省略*/


Photo映射文件

<class name="org.facelook.model.Photo" table="FACELOOKPHOTO" schema="YANGMENG">
/*其他省略*/
<property name="content" type="java.sql.Blob">
<column name="CONTENT" />
</property>
<property name="thumbnail" type="java.sql.Blob">
<column name="THUMBNAIL" />
</property>

oracle中的blob类型,在实体类中使用java.sql.Blob对应。
从数据库查询数据时正常写查询方法就可以,在页面中输出图片时,在img标签的src属性写要访问的路径,我这里是PhotoAction的thumb方法。

[img]photo_thumb?id=<s:property value='photo.id'/>[/img]

PhotoAction的thumb方法

public String thumb(){
try {
this.photo = this.pService.getById(this.id);
this.contentType = this.photo.getContentType();
this.inputStream = this.photo.getContent().getBinaryStream();
} catch (SQLException e) {
e.printStackTrace();
}
return "thumb";
}

struts.xml

<action name="photo_*" class="PhotoAction" method="{1}">
<result name="thumb" type="stream">
<param name="contentType">${contentType}</param>
<param name="bufferSize">1024</param>
</result>
</action>

其中contentType是下载类型,读取的图片所以${contentType}值为image/jpeg。
这样图片就从数据库中读取出来了。以上是使用struts2的方法。如果不使用struts2来实现也可以使用流输出出来。代码如下:

this.photo = this.pService.getById(this.id);
response.setContentType(this.photo.getContentType());//this.photo.getContentType()值为image/jpeg
ServletOutputStream op = response.getOutputStream();
InputStream is = this.photo.getContent().getBinaryStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedImage bi = ImageIO.read(bis);
JPEGImageEncoderImpl jpeg = new JPEGImageEncoderImpl(op);
jpeg.encode(bi);
op.close();
response.flushBuffer();
out.clear();
out = pageContext.pushBody();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值