JAVA 数据库读取blob(图片)合成多张图 基于Struts2和Spring

2023-10-27

今天工作要求把存在数据库的图片(blob)读取出来,之前没有做过所以找了不少资源,在这里记录一下。因为用的是jdbcTemplate,在这里一起贴出来,以防忘了。因为数据库查出来的图片是多张图,在这里返回List,到前台再转成byte[]。有些方法是在查询时直接转成byte[]返回到页面,但这样只能返回一张图片。

'''

[@Resource](https://my.oschina.net/u/929718)
private JdbcTemplate jdbcTemplate;

[@Override](https://my.oschina.net/u/1162528)
public List<Blob> getPicture(String picid) throws Exception {
	final List<Blob> list = new ArrayList<Blob>();
	String sql = "select picture from pic where picid = ? ";
	Object[] params = new Object[]{picid};
	jdbcTemplate.query(sql, params,new RowMapper(){
		public Object mapRow(ResultSet rs,int index)throws SQLException{
			Blob img = rs.getBlob(1);
			list.add(img);
			return null;
		}
	});
	if(list!=null&&list.size()>0){
		return list;
	}else{
		return null;
	}
}

'''

因文在service层只是单纯的调用,就不贴出来了。在action层调用方法后,返回List<Blob>,用blob.getBinaryStream()获取InputStream,再将inputStream写入缓冲流BufferedInputStream,最后用ImageIO读取,并由ImageIO.read()传输到前台页面。 显而易见,如果是一张图片直接用上述方法传输就可以,但如果是多张图片,就会被覆盖。所以需要将图片拼在一起。因为工作要求,不可以存图片在服务器上,所以这里用流直接拼接图片,参考了网上的方法,自己改了一点就ok了。

'''

public String getBlob() throws Exception{
List<Blob> blobs = gbs.getPicture(fileid);
	List<BufferedImage> images = new ArrayList<BufferedImage>();
	if(blobs!=null){
		for(int i=0;i<blobs.size();i++){
			//数据库拿到的blob转bufferedimage
			InputStream in = blobs.get(i).getBinaryStream();
			BufferedImage image = null;
			BufferedInputStream ins = new BufferedInputStream(in);
			image = ImageIO.read(ins);
			if(image!=null){
				images.add(image);
			}
		}
	}
	BufferedImage imagenew = yMerge("PNG",images);//Java纵向拼接多张图片
	if(imagenew!=null){
		//写入前台
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("image/png");
		response.setHeader("Pragma", "No-cache"); 
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		ImageIO.write(imagenew, "PNG", response.getOutputStream());
	}
	return null;
}
}
/**
 * Java纵向拼接多张图片
 *
 * [@param](https://my.oschina.net/u/2303379) imgs
 * [@param](https://my.oschina.net/u/2303379) type 图片类型
 * [@param](https://my.oschina.net/u/2303379) dst_pic
 * @return
 */
public static BufferedImage yMerge(String type, List<BufferedImage> images) {
    //获取需要拼接的图片长度
    int len = images.size();
    //判断长度是否大于0
    if (len < 1) {
        return null;
    }
    int[][] ImageArrays = new int[len][];
    for (int i = 0; i < len; i++) {
        int width = images.get(i).getWidth();
        int height = images.get(i).getHeight();
        // 从图片中读取RGB 像素
        ImageArrays[i] = new int[width * height];
        ImageArrays[i] = images.get(i).getRGB(0, 0, width, height, ImageArrays[i], 0, width);
    }

    int dst_height = 0;
    int dst_width = images.get(0).getWidth();
    //合成图片像素
    for (int i = 0; i < len; i++) {
        dst_width = dst_width > images.get(i).getWidth() ? dst_width : images.get(i).getWidth();
        dst_height += images.get(i).getHeight();
    }
    
    //合成后的图片
    if (dst_height < 1) {
        return null;
    }
    // 生成新图片
    BufferedImage ImageNew = null;
    try {
        ImageNew = new BufferedImage(dst_width, dst_height,BufferedImage.TYPE_INT_ARGB);
        //TYPE_INT_ARGB:生成图片的背景色为透明
        int height_i = 0;
        for (int i = 0; i < images.size(); i++) {
            ImageNew.setRGB(0, height_i, images.get(i).getWidth(), images.get(i).getHeight(),
            		ImageArrays[i], 0, images.get(i).getWidth());// dst_width
            height_i += images.get(i).getHeight();
        }

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return ImageNew;
}

'''

struts2中配置

'''

	<action name = "getPicture" class = "getPictureAction" method = "getPicture">
		<result name="success" type="stream">
			<!-- 文件格式定义 -->
			<param name="contentType">application/octet-stream</param>
			<param name="inputName">inputStream</param>
			<param name="contentDisposition">attachment;filename=${fileName}</param>
			<param name="bufferSize">1024</param>
		</result>
	</action>

'''

JSP页面

<img alt="图片" src="<%=basePath%>/getPicture.action">

参考文章:https://blog.csdn.net/luckgl/article/details/77054218

转载于:https://my.oschina.net/u/3272626/blog/2050702

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JAVA 数据库读取blob(图片)合成多张图 基于Struts2和Spring 的相关文章

随机推荐