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.
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();
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