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.
URL url = new URL(imagePath); ByteArrayOutputStream output = new ByteArrayOutputStream(); URLConnection conn = url. openConnection(); conn. setRequestProperty("User-Agent", "Firefox"); try (InputStream inputStream = conn. getInputStream()) { int n = 0; byte[] buffer = new byte[1024]; while (-1 !=
A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.
The IOUtils type has a static method to read an InputStream and return a byte[] . InputStream is; byte[] bytes = IOUtils. toByteArray(is); Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray() .
There's no guarantee that the content length you're provided is actually correct. Try something akin to the following:
ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = null; try { is = url.openStream (); byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time. int n; while ( (n = is.read(byteChunk)) > 0 ) { baos.write(byteChunk, 0, n); } } catch (IOException e) { System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage()); e.printStackTrace (); // Perform any other exception handling that's appropriate. } finally { if (is != null) { is.close(); } }
You'll then have the image data in baos
, from which you can get a byte array by calling baos.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With