您的位置:首页 > 其它

项目中图片处理总结

2011-11-09 21:36 351 查看

项目中图片处理总结

项目中的图片处理方案:1、将图片保存到项目中的image文件夹底下(这是最初的设计,当时考虑这样页面获取图片比较简单)2、将图片保存的物理磁盘上,相对于项目路径(将第一种方案改为第二种方案的原因是考虑到包替换的时候会把原来的图片替换掉。版本升级和包替换都不方便)3、将图片保存到物理磁盘、固定盘符、固定文件夹底下(将第二总方案改为第三中方案的原因是考虑到双机,必须把图片保存到共享磁盘上)4、将图片保存到数据库(没使用这总方法,原因是这总方法的占用数据库的空间,读取的时候也有性能问题)5、将图片保存到图片服务器(可惜本项目没有图片服务器)下面保存图片
//先保存图片到服务器
if (imageBean.getImageFile() != null && imageBean.getImageFile().length() > 0)
{
//得到图片名称
String imageName = imageBean.getImageFileFileName();
File file = imageBean.getImageFile();
//获取图片后缀
String ext = imageName.substring(imageName.lastIndexOf('.') + 1).toLowerCase(Locale.CHINA);
//重新生成文件名
String filename = UUID.randomUUID().toString() + "." + ext;//构建文件名称
//构建文件保存的目录 这是方案一的实现
//String pathdir = "/images/room/prototype";
//得到图片保存目录的真实路径 这是方案二的实现
//String realpathdir = new File(suiteImagePath).getCanonicalFile().getPath();
//String realpathdir = ServletActionContext.getServletContext().getRealPath(pathdir);
//FileTools.saveFile(file, realpathdir, filename);
//这个方法是保存文件到对应的路径
FileTools.saveFile(file, suiteImagePath, filename);
imageBean.setName(filename);
imageBean.setPullpath(suiteImagePath + "/" + filename);
}
//保存图片到数据库
int id = imageDAO.addImage(imageBean);
imageBean.setId(id);
return imageBean;
struts2具体如何上传文件这就不多说了、 保存图片就这么解决了。接下来看下页面如何获取图片
<img src="../showImage.action?imagePath=${imageBean.pullpath}" />

后台的处理是
InputStream file = null;
OutputStream toClient = null;
try
{
//imagePath = new File(imagePath).getCanonicalFile().getPath();
file = new FileInputStream(new File(imagePath));
//int i = file.available(); // 得到文件大小
byte data[] = new byte[KeyConstant.DEFAULT_BYTE_SIZE];
int endFlag = 0;
ServletActionContext.getResponse().setContentType("image/*"); // 设置返回的文件类型
toClient = ServletActionContext.getResponse().getOutputStream(); // 得到向客户端输出二进制数据的对象
while (endFlag != -1)
{
endFlag = file.read(data);
if (endFlag == -1)
{
break;
}
toClient.write(data, 0, endFlag); // 输出数据
}
toClient.flush();
toClient.close();
}
...后面是处理异常和关闭流
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: