I have had a ton of trouble figuring this out, and I've read so many tutorials and countless forum posts, but I'm convinced there's a good way to do this. We dynamically generate a BufferedImage in memory, and originally we wrote them out to a flat file (both a PNG and a JPEG version of the same image), but now that we're moving to Oracle, we want to write them straight into the database.
The problem is, when you use ImageIO to write the BufferedImage into a particular format (e.g. PNG or JPEG), you must send it to an OutputStream. When you want to insert a BLOB into the database using a PreparedStatement, you can use the setBinaryStream method that takes an InputStream and a byte count (int) of the image. I've been trying to figure out how to get the OutputStream that ImageIO writes to channeled into the InputStream that setBinaryStream takes in. I've researched PipedInputStream & PipedOutputStream and tried to use them, but always got broken pipes, either because of my incorrect use of them or because PreparedStatement didn't know how to read the stream properly since the ends of the pipe are in different threads.
It's really annoying because writing the image out to the filesystem generally takes about as much time as everything else together (generating the image, reading it in from file, and storing it in the db). Isn't there a better/easier way?