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

今天工作要求把存在数据库的图片(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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用以下的 Java 工具类实现将 Oracle 数据库中的 Blob 类型的照片读取出来,并且重命名保存到本地目录: ```java import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class OracleBlobImageSaver { public static void main(String[] args) { String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle 数据库连接URL String username = "your_username"; // 数据库用户名 String password = "your_password"; // 数据库密码 String sql = "SELECT photo_blob, photo_name FROM photo_table"; // 查询照片的SQL语句 String saveDir = "C:/path/to/save/directory/"; // 保存照片的本地目录 try (Connection conn = DriverManager.getConnection(url, username, password); PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { Blob blob = rs.getBlob("photo_blob"); String fileName = rs.getString("photo_name"); File file = new File(saveDir + fileName); try (InputStream in = blob.getBinaryStream(); FileOutputStream out = new FileOutputStream(file)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } System.out.println("Photo saved: " + file.getAbsolutePath()); } } } catch (Exception e) { e.printStackTrace(); } } } ``` 需要注意的是,你需要将 `your_username` 和 `your_password` 替换为你的数据库的实际用户名和密码。另外,你需要根据你的实际情况修改连接字符串 `url`、查询语句 `sql` 和保存目录 `saveDir`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值