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(bitma开发者_运维百科pFromByteArray);
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 InputStream
into a byte array?
You can do this directly with a loop that calls InputStream#read
into 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:
byte[] bytes = null;
try {
bytes = IOUtils.toByteArray(conn.getInputStream());
} catch (IOException e) {
// handle the exception
}
toByteArray
uses a ByteArrayOutputStream
to avoid allocating an array up-front, but you wouldn't need to worry about this.
byte[] ba = new byte[is.available()];
It's not that way you'll get the required bytes. The easiest way to get that bytes is to use Apache commons (IOUtils). Your second approach decodes the bitmap directly from the HTTP input stream. It's also possible but it's better to download it first and than decode. Also you don't need to compress the bitmap after decoding. Just use it.- Bitmap should be recycled when it's not used. I don't think you can call
bitmapFromByteArray.recycle();
from that place you do it.
精彩评论