2014-01-06 77 views
0

我在內存中有一個Image(類型:java.awt.Image),我想使用jdk 1.7將它轉換爲Blob(類型:java.sql.Blob)。將內存中的圖像轉換爲Blob

我一直在這個問題上找到的所有東西都使用流和文件。當然,我不需要將這個圖像保存到文件,然後才能轉換它?

這裏不多顯示,但一個例子如下:

進口的java.sql.Blob; import java.awt.Image;

public GenericResponseType savePhoto(Image image) 
{ 
     Connection conn = ds.getConnection(); 

     << some DB code and assembly of PreparedStatement >> 

     Blob blob = conn.createBlob(); 

      << here's where the magic needs to happen I need to get the image parameter to blob >> 
      // I've tried the following but doesn't quite work as it wants a RenderedImage 
     // OutputStream os = blob.setBinaryStream(1); 
     // ImageIO.write(parameters.getPhoto().getImage(), "jpg", os); 


     pstmt.setBlob(4, blob); 
    } 

一些更詳細的(雖然我懷疑它的問題了)就是上面生成使用Web服務/ JAX-WS從WSDL與操作使用MTOM聲明。因此它會生成一個帶有作爲變量傳遞的圖像的簽名。

+2

不,但您需要首先將其放入BufferedImage – MadProgrammer

回答

2

java.awt.Image很簡單。它沒有提供任何可以寫入/保存圖像的手段,也沒有提供任何手段來訪問圖像的底層像素數據。

第一步,將java.awt.Image轉換爲ImageIO可以支持的東西。這將允許您將圖像數據寫出...

ImageIO需要RenderedImage作爲其主要圖像源。 BufferedImage是默認庫中此接口的唯一實現...

不幸的是,沒有簡單的從一個轉換到另一個的方法。幸運的是,這並不難。

Image img = ...; 

BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); 
Graphics2D g2d = bi.createGraphics(); 
g2d.drawImage(img, 0, 0, null); 
g2d.dispose(); 

基本上,這只是油漆原java.awt.ImageBufferedImage

接下來,我們需要將圖像保存在某種程度上,這樣它可以產生一個InputStream ...

這是一個稍微不那麼理想,但完成了工作。

ByteArrayOutputStream baos = null; 
try { 
    baos = new ByteArrayOutputStream(); 
    ImageIO.write(bi, "png", baos); 
} finally { 
    try { 
     baos.close(); 
    } catch (Exception e) { 
    } 
} 
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); 

基本上,我們寫出來的圖像爲ByteArrayOutputStream和使用結果生成一個ByteArrayInputStream

現在。如果記憶是一個問題,或圖像是相當大的,你可以先在圖像寫入File,然後簡單地通過某種InputStream,而不是閱讀File回...

最後,我們設置InputStream到所需的列...

PreparedStatement stmt = null; 
//...  
stmt.setBlob(parameterIndex, bais); 

和BLOB的你大爺......

+0

非常感謝。我曾將上述看作是一種可能的方法,但對於表面上看起來應該非常簡單的東西來說,似乎太多了。我可能不得不使用文件IO。 – user3167187

0

嘗試以下方法:(可能是更容易的過程,這正是我一個快速GOOLGE後發現並不能保證它會工作 - 馬茲答案看起來更可信)。

  1. 獲得一個BufferedImage(From this answer

    BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE); 
    buffered.getGraphics().drawImage(image, 0, 0 , null); 
    
  2. 獲取一個字節數組(From this answer

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ImageIO.write(buffered, "jpg", baos); 
    byte[] imageInByte = baos.toByteArray(); 
    
  3. 保存字節數組作爲BLOB(From this answer)(但應該使用編寫聲明)

    Blob blob = connection.createBlob(); 
    blob.setBytes(1, imageInByte);