0

For one of the implementation, from Java code I am hitting labelary Rest service to convert ZPL formatted code to Image. I am able to successfully fetch the response. But I am not able to convert the HttpResponse to image file.

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost "http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/"); 
byte[] byteArray = Base64.decodeBase64(base64Val.getBytes());
String decodedString = new String(byteArray);
StringEntity requestEntity;
try {
requestEntity = new StringEntity(decodedString);
requestEntity.setContentType("application/x-www-form-urlencoded");
post.setEntity(requestEntity);
HttpResponse response = client.execute(post);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
#Need suggestions to convert BufferReader to Image
}

Post referring the suggested answer, code looks like:

HttpResponse response = client.execute(post); InputStream inStream = response.getEntity().getContent(); String dataString = convertStreamToString(inStream); byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(dataString); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes)); File outputfile = new File("myImage.png"); ImageIO.write(image, "png", outputfile);

  • [check this answer](https://stackoverflow.com/a/50682688/7051704) i think this is the solution you want – paulrda Jul 25 '18 at 09:18
  • Thanks for the reference.. I used the same code that you had shared. But its failing during the conversion of data string to imagebytes. In debug I can see dataString is not null, still I see "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:". Please advise further. – user3440451 Jul 25 '18 at 09:37
  • I see datastring starting : ‰PNG and then the rest of the string is not readable. Please help. – user3440451 Jul 25 '18 at 09:57
  • @paulrda Please help. – user3440451 Jul 25 '18 at 10:18

1 Answers1

0

use this byte to image converter. past value in datastring and check whether you get the image.

paulrda
  • 61
  • 1
  • 2
  • 7
  • The dataString is actually in ASCII format. Code snippet for reference: – user3440451 Jul 25 '18 at 10:51
  • Edited my question to post the latest code snippet. Here the data type conversion to byte array is failing with 'Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8218. I think post successful conversion to byte array it can be tested with the URL you had suggested. Please help me here. – user3440451 Jul 25 '18 at 10:56