开发者

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

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 I开发者_JAVA百科mageInputStream 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());


Have you tried writing to a ByteArrayOutputStream and then creating a ByteArrayInputStream from that data to read from? (Call toArray on the ByteArrayOutputStream and then call the constructor of ByteArrayInputStream which will wrap that byte array.)


Be careful using BytArray streams: if the image is large, that code will fail. i have not done much applet coding, but it's possible that the temp dir is available for writing (e.g. File.createTempFile() ).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜