0

I had stored TIFF image in BFILE (oracle 10G). I want to read it from database and create .tiff image to local directory. (I am using JAI). Following is my code where ImageIO.read() returns null.

OraclePreparedStatement  pst = 
(OraclePreparedStatement)con.prepareStatement("select chq_tif_img from 
mstr where id = 52");

ResultSet rs = pst.executeQuery();

if(rs.next())
{   
    bfile = ((OracleResultSet)rs).getBFILE ("chq_tif_img ");    
    bfile.openFile();   

    System.out.println("BFILE: getDirAlias() = " + bfile.getDirAlias());
    System.out.println("BFILE: getName() = " + bfile.getName());
    System.out.println("BFILE: fileExists() = " + bfile.fileExists());
    System.out.println("BFILE: isFileOpen() = " + bfile.isFileOpen());
    System.out.println("BFILE: length = " + bfile.length());
    InputStream inputStream = bfile.getBinaryStream();
    System.out.println("-->"+inputStream);
    BufferedImage bi = ImageIO.read(inputStream);
    TIFFEncodeParam    params_omg=   new TIFFEncodeParam();
    FileOutputStream   os_omg    =   new FileOutputStream("anand.tiff");
    javax.media.jai.JAI.create("encode", bi, os_omg, "TIFF", params_omg);

    inputStream.close();
    bfile.closeFile();
}

I had searched here but I couldn't get exact help on reading TIFF from database and create .tiff image file. Please help me.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anand B.
  • 1
  • 2
  • Don't use JAI or `ImageIO` to copy files, they are not very good at it. :-) Just copy the contents of the `inputStream` directly to disk. See for example [this answer](http://stackoverflow.com/a/29005856/1428606) for how to copy a file byte by byte. – Harald K Oct 14 '16 at 12:41

1 Answers1

0

As mentioned in my comment, you shouldn't use JAI or ImageIO to copy files, they are not very good at it. :-)

Instead, it's much faster and more compatible to just copy the contents of the InputStream directly to disk (ie. a FileOutputStream).

Modifying your code along the lines of my comment, you will get:

OraclePreparedStatement  pst = 
(OraclePreparedStatement)con.prepareStatement("select chq_tif_img from 
mstr where id = 52");

ResultSet rs = pst.executeQuery();

if(rs.next())
{   
    bfile = ((OracleResultSet)rs).getBFILE ("chq_tif_img ");    
    bfile.openFile();   

    // Skipping debug output for brevity

    try (InputStream inputStream = bfile.getBinaryStream();
         OutputStream   os_omg = new FileOutputStream("anand.tiff")) {
        FileUtils.copy(inputStream, os_omg);
    }
    finally {
        bfile.closeFile(); // Make sure you always close the file when done
    }
}

FileUtils.copy can be implemented as:

public void copy(final InputStream in, final OutputStream out) {
    byte[] buffer = new byte[1024]; 
    int count;

    while ((count = in.read(buffer)) != -1) {
        out.write(buffer, 0, count);
    }

    // Flush out stream, to write any remaining buffered data
    out.flush();
}
Harald K
  • 26,314
  • 7
  • 65
  • 111