0

I'm consuming a .NET json service that outputs a byte array. The byte arrary gets converted into the integer representation of each byte. When viewed in Fiddler, it looks like this:

{"imageBackground":[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,...]}

In Java, I've got the data back into a JSONObject, but I'm unfamiliar with Java so I'm not sure where to go from here to convert that into something usable. I suspect if I can get it back into a stream of some sort I should be able to make it viewable as an image (PNG/JPG/etc)...

Any tips form here?

1
  • I'm a little disturbed by the idea that anybody is sending an image that way in the first place. (A JSON string of Base64'ed data would be much better.) Commented Jun 17, 2011 at 19:11

2 Answers 2

2

Get imageBackground as a byte array, and then hand it off to ImageIO:

byte[] imageBackground = // set me here;
ByteArrayInputStream input = new ByteArrayInputStream(imageBackground);
try {
    BufferedImage ImageIO.read(input);
    // do fun stuff with the image...
}
finally {
    input.close();
}

I'm not sure what your application wants to do as the image, but once you have a BufferedImage you can use ImageIO to convert it to another type, you can do transforms, output to a file...the sky's the limit. You can find a tutorial for that and more by Googling.

Sign up to request clarification or add additional context in comments.

3 Comments

@Andrew Heh heh...I know the feeling.
Are there any java functions available to facilitate getting the string of integers back into a byte[]?
certainly... String.getBytes(). there are two signatures...one which returns in the default character encoding (UTF-16) and another where you can specify the encoding.
0

Something like this (the methods names are probably incorrect, don't know them from the top of my head)

JSONArray jBytes = theObject.getArray("imageBackground");
byte[] imData = new byte[jBytes.size()];
for (int i = 0; i < jBytes.size(); i++) {
   imData[i] = jBytes.get(i);
}

That's how you make it a real byte array. Then do what stevevls posted, or whatever you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.