2011-01-31 119 views
13

对于我正在处理的小程序,我需要将BufferedImage文件转换为输入流,以便我可以将图像上载到我的MySQL服务器。本来我是用这个代码:Java将图像转换为输入流而不创建文件

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"); 
} 

(同时捕捉相关的异常)的代码挂在那里的小程序试图将图像保存到计算机的一部分。代码在Eclipse中完美工作,或者每当我从本地主机运行applet时,所以我假设问题在于applet将文件保存到用户计算机的权限。

我只是想知道是否有办法将图像文件转换为输入流而不必将文件保存到用户的计算机。我试着使用:

ImageIO.createImageInputStream(image); 

但我不能转换ImageInputStream回到一个InputStream。有什么建议么?

谢谢!

+2

argh!从数据库中读取相同的代码会执行图像处理!这太可怕了。请阅读:[Cohesion](http://en.wikipedia.org/wiki/Cohesion_(computer_science)),[Coupling](http://en.wikipedia.org/wiki/Coupling_(computer_science)) – 2011-01-31 17:32:33

+0

是的不是最佳做法。感谢您的信息,我将不得不稍后解决。 – David 2011-01-31 17:48:02

+0

[如何将BufferedImage转换为InputStream?](http://stackoverflow.com/questions/4251383/how-to-convert-bufferedimage-to-inputstream) – 2015-11-11 10:04:26

回答

26

通常,您会为此使用ByteArrayOutputStream。它充当内存中的流。

ByteArrayOutputStream os = new ByteArrayOutputStream(); 
ImageIO.write(image,"png", os); 
InputStream fis = new ByteArrayInputStream(os.toByteArray()); 
1

您是否尝试写入ByteArrayOutputStream,然后从该数据创建ByteArrayInputStream以读取? (在ByteArrayOutputStream上调用toArray,然后调用将包装该字节数组的ByteArrayInputStream的构造函数。)

+2

感谢您的建议,这基本上是我结束了但是其他答案实际上是喂宝宝给我的代码。 :P – David 2011-01-31 17:48:48

1

小心使用BytArray流:如果图像很大,代码将失败。我没有做太多的小程序编码,但可能有临时目录可用于编写(例如File.createTempFile())。