I’m trying to read an image from an URL (with the Java package
java.net.URL) to a byte[]. "Everything" works fine, except that the content isn’t being entirely read from the stream (the image is corrupt, it doesn’t contain all the image data)… The byte array is being persisted in a database (BLOB). I really don’t know what the correct approach is, maybe you can give me a tip. 🙂
This is my first approach (code formatted, removed unnecessary information…):
URL u = new URL("http://localhost:8080/images/anImage.jpg");
int contentLength = u.openConnection().getContentLength();
Inputstream openStream = u.openStream();
byte[] binaryData = new byte[contentLength];
openStream.read(binaryData);
openStream.close();
My second approach was this one (as you’ll see the contentlength is being fetched another way):
URL u = new URL(content);
openStream = u.openStream();
int contentLength = openStream.available();
byte[] binaryData = new byte[contentLength];
openStream.read(binaryData);
openStream.close();
Both of the code result in a corrupted image…
I already read this post from Stack Overflow.
There’s no guarantee that the content length you’re provided is actually correct. Try something akin to the following:
You’ll then have the image data in
baos, from which you can get a byte array by callingbaos.toByteArray().This code is untested (I just wrote it in the answer box), but it’s a reasonably close approximation to what I think you’re after.