2011-01-31 54 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())。

相關問題