Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java converting an image to an input stream WITHOUT creating a file

Tags:

java

image

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!

like image 221
David Avatar asked Jan 31 '11 17:01

David


1 Answers

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());
like image 116
Carles Barrobés Avatar answered Oct 12 '22 03:10

Carles Barrobés