bakua
bakua

Reputation: 14464

How to download image file with unknown length on android

I'm trying to display file from local network url

http://192.168.1.118:1881/image.jpg

and display it immidiatelly in ImageView. Problem is that when I open inputStream for this url and try to decode it with BitmapFactory I get null Bitmap. I suppose that is because I get this message from input stream: libcore.net.http.UnknownLengthHttpInputStream.

That image is supported and hosted by server app which I can't modify.

Thanks very much, I've tried hard and looked for solutions, but nothing works for me

Upvotes: 0

Views: 1092

Answers (2)

Daniel Johansson
Daniel Johansson

Reputation: 760

Download it to a byte array and decode the byte array:

byte[] data = read(inputStreamFromConnection);
if (data != null) {
    Bitmap downloadedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}

public static byte[] read(InputStream is) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
    try {
        // Read buffer, to read a big chunk at a time. 
        byte[] buf = new byte[2048];
        int len;
        // Read until -1 is returned, i.e. stream ended.
        while ((len = is.read(buf)) != -1) {
            baos.write(buf, 0, len);
        }
    } catch (IOException e) {
        Log.e("Downloader", "File could not be downloaded", e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            // Input stream could not be closed.
        }
    }
    return baos.toByteArray();
}

Upvotes: 1

Jong
Jong

Reputation: 9125

Try to download the full image, then show it after the download is completed. For example, write all the downloaded bytes to an array then use BitmapFactory.decodeByteArray. Or save the image to a temporary file, then use BitmapFactory.decodeFile and then delete that file.

Upvotes: 0

Related Questions