Sheldon Sheldon - 1 year ago 72
MySQL Question

Retrieve an Image stored as BLOB on a MYSQL DB

I'm trying to create a PDF based on the information that resides on a database. Know I need to retrieve a TIFF image that is stored as a BLOB on a mysql database from Java. And I don't know how to do it. The examples I've found shows how to retrieve it and save it as a File (but on disk) and I needed to reside on memory.


BLOB Field name: IMAGEN

Any Ideas?

Answer Source

On your ResultSet call:

Blob imageBlob = resultSet.getBlob(yourBlobColumnIndex);
InputStream binaryStream = imageBlob.getBinaryStream(0, imageBlob.length());

Alternatively, you can call:

byte[] imageBytes = imageBlob.getBytes(1, (int) imageBlob.length());

As BalusC noted in his comment, you'd better use:

InputStream binaryStream = resultSet.getBinaryStream(yourBlobColumnIndex);

And then the code depends on how you are going to read and embed the image.