首页 > 代码库 > java blob存取图片

java blob存取图片

1. 存入图片

        Connection con=db.conn;
        PreparedStatement pstmt;
        //File file = upload;
        FileInputStream inputImage = new FileInputStream(upload);
        byte[] buf = new byte[inputImage.available()];
        inputImage.read(buf);
        con.setAutoCommit(false);
        System.out.println("**before sql**");
        try {
            pstmt = con.prepareStatement("insert into zzbj_rs_region_detail(id,region_Id,coordinate1,coordinate2,coordinate3,table_Name,rs_id,icon,createTime) values("
                            + rdb.getId()+ ","+ rdb.getRegionId()+ ","+ rdb.getCoor1()+ ","+ rdb.getCoor2()+ ","+ rdb.getCoor3()+ ",‘"
                            + rdb.getTableName()+ "‘,"+ rdb.getRsId() + ",empty_blob(),sysdate)");//先存入空blob 再修改,可以存入大的图片,首次插入有大小限制,小图片没问题,大了就会报异常
            pstmt.executeUpdate();
            System.out.println("**afer sql**");
            ResultSet rs = pstmt.executeQuery("SELECT icon FROM zzbj_rs_region_detail where id="+ rdb.getId() + " for update");
            if (rs.next()) {
                oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("icon");
                OutputStream out = blob.getBinaryOutputStream();
                out.write(buf);
                out.flush();
                out.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        con.commit();

2. 修改图片

 1 FileInputStream inputImage = new FileInputStream(upload);
 2                 byte[] buf = new byte[inputImage.available()];
 3                 inputImage.read(buf);
 4                 con.setAutoCommit(false);
 5                 PreparedStatement pst=con.prepareStatement("SELECT icon FROM zzbj_rs_region_detail where id="+ rdb.getId() + " for update");
 6                 ResultSet rs = pst.executeQuery();
 7                 if (rs.next()) {
 8                     oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("icon");
 9                     OutputStream out = blob.getBinaryOutputStream();
10                     out.write(buf);
11                     out.flush();
12                     out.close();
13                 }
14                  con.commit();

3.  读取图片

        Connection con=db.conn;
        Statement stmt = con.createStatement();
        String sql = "select background from zzbj_rs_region where id=‘"+id+"‘ ";
        ResultSet rs =db.query(sql);
          if (rs.next()){
           oracle.sql.BLOB b = (oracle.sql.BLOB) rs.getBlob("background");
           long size = b.length();
           byte[] bs = b.getBytes(1, (int) size);
           res.setContentType("image/jpeg");
           OutputStream outs = res.getOutputStream();
          if(size>1){
           outs.write(bs);      
           outs.flush();}          
           db.closeDb();
           }