------------------------------------------------------------------------------------
action代码:
private File fileInfo;
//添加图片
public String addPhoto() throws Exception
{
FileInputStream in = new
FileInputStream(fileInfo);
//设置原图
photo.setPhobyte(Hibernate.createBlob(in));
//原图转换-不要从Photo.getPhobyte里取
FileInputStream in1 = new
FileInputStream(fileInfo);
Blob bol=Hibernate.createBlob(in1);
BufferedImage
bid1=ImageIO.read(bol.getBinaryStream());
//生成缩略图
BufferedImage
bid2=this.resize(bid1,100,100);
//设置缩略图
ByteArrayOutputStream baos = new
ByteArrayOutputStream();
ImageIO.write(bid2, "jpeg", baos);
//给Photo赋值
photo.setPhtbreviary(Hibernate.createBlob(baos.toByteArray()));
photo.setCreatetime(new Date());
photo.setPhoorder(5);
photo.setPhotype("jsp");
// 设置相册
Album album = new Album();
album.setAlbumid(1000);
photo.setAlbum(album);
photoService.addPhoto(photo);
return SUCCESS;
}
//生成缩略图
public static BufferedImage
resize(BufferedImage source, int targetW,int targetH) {
// targetW,targetH 分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW /
source.getWidth();
double sy = (double) targetH /
source.getHeight();
// 这里想实现在 targetW,targetH
范围内实现等比缩放。如果不需要等比缩放
// 则将下面的 if else 语句注释即可
// if (sx > sy) {
// sx = sy;
// targetW = (int) (sx *
source.getWidth());
// } else {
// sy = sx;
// targetH = (int) (sy *
source.getHeight());
// }
if (type == BufferedImage.TYPE_CUSTOM) { //
handmade
ColorModel cm =
source.getColorModel();
WritableRaster raster =
cm.createCompatibleWritableRaster(targetW,
targetH);
boolean alphaPremultiplied =
cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster,
alphaPremultiplied, null);
} else
target = new BufferedImage(targetW,
targetH, type);
Graphics2D g =
target.createGraphics();
// smoother than exlax: 3
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.drawRenderedImage(source,
AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}
-----------------------------------------------------------------------------------------------------
jsp页面: