Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to download a .png file using Async and set it to ImageView?

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.

like image 811
Egor Avatar asked Dec 17 '22 23:12

Egor


1 Answers

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();
like image 187
Sephy Avatar answered Dec 28 '22 08:12

Sephy