For an applet I'm working on I need to convert a BufferedImage file to an input stream so that I can upload the image to my MySQL server. Originally I was using this code: 
Class.forName("com.mysql.jdbc.Driver").newInstance();  
Connection connection = 
    DriverManager.getConnection(connectionURL, "user", "pass");  
psmnt = connection.prepareStatement(
    "insert into save_image(user, image) values(?,?)");  
psmnt.setString(1, username);  
ImageIO.write(image, "png", new File("C://image.png")); 
File imageFile = new File("C://image.png");
FileInputStream fis = new FileInputStream(imageFile);
psmnt.setBinaryStream(2, (InputStream)fis, (fis.length()));
int s = psmnt.executeUpdate();
if(s > 0) {
  System.out.println("done");
}
(while catching the relevant exceptions) The code hangs on the part where the applet attempts to save the image to the computer. The code worked perfectly in Eclipse or whenever I ran the applet from the localhost, so I'm assuming the problem is in the privileges that the applet has in saving files to the user's computer.
I was just was wondering if there was a way to turn the image file into an inputstream without having to save a file to the user's computer. I tried using:
ImageIO.createImageInputStream(image);
But then I couldn't convert the ImageInputStream back to an InputStream. Any Suggestions?
Thanks!
Typically you would use a ByteArrayOutputStream for that purpose. It acts as an in-memory stream.
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image,"png", os); 
InputStream fis = new ByteArrayInputStream(os.toByteArray());
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With