I’m trying to download a jpg image from the web saving it into a byte array in order to have the compressed image on the ram until I have to show it, but I’m getting a black picture.
What I’m doing is:
URL myFileUrl =null;
myFileUrl= new URL(fileUrl);
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
conn.setUseCaches(false);
InputStream is = conn.getInputStream();
byte[] ba = new byte[is.available()];
After that I’m keeping the array in the RAM until I have to use it.
To place it, I do:
Bitmap bitmapFromByteArray = BitmapFactory.decodeByteArray(ba,0,ba.length);
imageView1.setImageBitmap(bitmapFromByteArray);
bitmapFromByteArray.recycle();
I solved the problem by doing
URL myFileUrl =null;
myFileUrl= new URL(fileUrl);
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
int size = bm.getWidth() * bm.getHeight();
ByteArrayOutputStream out = new ByteArrayOutputStream(size);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
byte[] ba2 = out.toByteArray();
bm.recycle()
Buut by doing this I’m decoding the JPEG and then re-encoding the image multiple times lowering the quality of the picture and using the phone resources longer than necessary. Also, the bitmap I get after re-encoding is bigger than the original jpg image.
Is there any way to get the first method to work?
Thank you.
Are you trying to simply copy the content of an
InputStreaminto a byte array?You can do this directly with a loop that calls
InputStream#readinto a byte array, or you can leave the implementation up to others by using IOUtils.toByteArray from Apache commons.Edit – You don’t need to deal with array initialization if you use the Apache commons method:
toByteArrayuses aByteArrayOutputStreamto avoid allocating an array up-front, but you wouldn’t need to worry about this.