Reputation: 61
I've got the URL of a .png image, that needs to be downloaded and set as a source of an ImageView. I'm a beginner so far, so there are a few things I don't understand: 1) Where do I store the file? 2) How do I set it to the ImageView in java code? 3) How to correctly override the AsyncTask methods?
Thanks in advance, will highly appreciate any kind of help.
Upvotes: 6
Views: 6599
Reputation: 2096
You can explicity build a png from a download.
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
100
is your compression (PNG's are generally lossless so 100%)
out
is your FileOutputStream to the file you want to save the png to.
Upvotes: 5
Reputation: 50442
I'm not sure you can explicity build a png from a download. However, here is what I use to download images and display them into Imageviews :
First, you download the image :
protected static byte[] imageByter(Context ctx, String strurl) {
try {
URL url = new URL(urlContactIcon + strurl);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And then, create a BitMap and associate it to the Imageview :
bytes = imagebyter(this, mUrl);
bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
yourImageview.setImageBitmap(bm);
And that's it.
EDIT
Actually, you can save the file by doing this :
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(imagebyter(this, mUrl));
fos.close();
Upvotes: 8