Tutorial :how to convert byte array to image in java?



Question:

I am developing a Web application in Java. In that application, I have created webservices in Java. In that webservice, I have created one webmethod which returns the image list in base64 format. The return type of the method is Vector. In webservice tester I can see the SOAP response as xsi:type="xs:base64Binary". Then I called this webmethod in my application. I used the following code:

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

In this code I am receiving the error:

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

Is there any mistake in my code? Or is there any other way to bring the image in actual format? Can you provide me the code or link through which I can resolve the above issue?

Note:- I already droped this question and I got the suggetion to try the following code

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

I tried this code and got the output as byte[] from webservice. but I am not able to convert this byte array to actual image. is there any other way to bring the image in actual format? Can you provide me the code or link through which I can resolve the above issue?


Solution:1

You can check this link which provides information about converting image to Byte[] and Byte[] back to image. Hope this helps you.

http://www.programcreek.com/2009/02/java-convert-image-to-byte-array-convert-byte-array-to-image/


Solution:2

To convert use Base64.decode;

String base64String = (String)itr.next();  byte[] bytearray = Base64.decode(base64String);    BufferedImage imag=ImageIO.read(bytearray);  


Solution:3

I'm not familiar with what you're trying to do, but I can say this: String does have a constructor that takes a byte[].

If I understood you correctly, you tried to do String s = (String) byteArray;, which of course doesn't work. You can try String s = new String(byteArray);.

Looking at the actual error message:

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

I'm saying that perhaps you meant to do:

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »