开发者

Download Image from url is sometimes returning null image

开发者 https://www.devze.com 2023-03-14 17:28 出处:网络
I am using the following code to download a bitmap from a url,: myFileUrl = new URL(fileUrl); HttpURLConnection conn = (HttpURLConnection) myFileUrl

I am using the following code to download a bitmap from a url,:


myFileUrl = new URL(fileUrl);


HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bmpTemp = BitmapFactory.decodeStream(is);

bu开发者_C百科t sometimes, I mean once in a hundred times, the bitmap is null! any body knows what might be the problem,

Thanks


There is a bug in the url connection. It has a fix that uses a FlushedInputStream decorator function for it. here is the code for it:

 /*
     * An InputStream that skips the exact number of bytes provided, unless it reaches EOF.
     */
    public static class FlushedInputStream extends FilterInputStream {

        public FlushedInputStream(InputStream inputStream) {
            super(inputStream);
        }
        @Override
        public long skip(long n) throws IOException {
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped < n) {
                long bytesSkipped = in.skip(n - totalBytesSkipped);
                if (bytesSkipped == 0L) {
                    int b = read();
                    if (b < 0) {
                        break;  // we reached EOF
                    } else {
                        bytesSkipped = 1; // we read one byte
                    }
                }
                totalBytesSkipped += bytesSkipped;
            }
            return totalBytesSkipped;
        }
    }

the usage is:

BitmapFactory.decodeStream(new FlushedInputStream(is));
0

精彩评论

暂无评论...
验证码 换一张
取 消