2010-03-12 49 views
2

我正在用Java開發一個Web應用程序。在那個應用程序中,我使用Java創建了Web服務。在該web服務中,我創建了一個web方法,它返回base64格式的圖像列表。該方法的返回類型是Vector。在web服務測試中,我可以看到SOAP響應爲xsi:type="xs:base64Binary"。然後我在我的應用程序中調用了這個webmethod。我用下面的代碼:如何將字節數組轉換爲java中的圖像?

SBTSWebService webService = null; 
List imageArray = null; 
List imageList = null; 
webService = new SBTSWebService(); 
imageArray = webService.getSBTSWebPort().getAddvertisementImage(); 
Iterator itr = imageArray.iterator(); 
while(itr.hasNext()) 
{ 
    String img = (String)itr.next(); 
    byte[] bytearray = Base64.decode(img); 
    BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray)); 
    imageList.add(imag); 
} 

在這段代碼中,我收到錯誤:

java.lang.ClassCastException: [B cannot be cast to java.lang.String" on line String img = (String)itr.next();

有沒有在我的代碼的任何錯誤?或者有沒有其他方法可以將圖像以實際的格式顯示出來?你能否提供我可以解決上述問題的代碼或鏈接?

注: - 我已經DROP掉這個問題,我得到了suggetion試試下面的代碼

Object next = iter.next(); 
System.out.println(next.getClass()) 

我想這個代碼,並得到了輸出byte[]從web服務。但我無法將此字節數組轉換爲實際圖像。 有沒有其他的方式來把圖像以實際的格式?你能否提供我可以解決上述問題的代碼或鏈接?

+0

請有人編輯這個問題,我不明白! ...正確編寫代碼。 – RubyDubee

回答

0

我不熟悉你想要做什麼,但我可以這樣說:String確實有一個構造函數一個byte[]

如果我正確地理解了你,你試過做String s = (String) byteArray;,這當然不起作用。你可以嘗試String s = new String(byteArray);

看實際的錯誤信息:

java.lang.ClassCastException: [B cannot be cast to java.lang.String 
    on line String img = (String)itr.next(); 

我是說也許意思做:

String img = new String(itr.next()); 
1

要轉換使用Base64.decode;

String base64String = (String)itr.next(); 
byte[] bytearray = Base64.decode(base64String); 

BufferedImage imag=ImageIO.read(bytearray); 
相關問題