I’m using BitmapFactory.decodeStream to load an image from a url in Android. I want to only download images below a certain size, and I’m currently using getContentLength to check this.
However, I’m told that getContentLength doesn’t always provide the size of the file, and in those cases I would like to stop the download as soon as I know that the file is too big. What is the right way to do this?
Here is my current code. I currently return null if getContentLength doesn’t provide an answer.
HttpGet httpRequest = new HttpGet(new URL(urlString).toURI());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
final long contentLength = bufHttpEntity.getContentLength();
if ((contentLength >= 0 && (maxLength == 0 || contentLength < maxLength))) {
InputStream is = bufHttpEntity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(is);
return new BitmapDrawable(bitmap);
} else {
return null;
}
You should use HttpHead to issue a HEAD request, which is similar to GET but will return only headers. If the content length is satisfactory, then you can make your GET request to get the content.
The majority of servers should handle HEAD requests without a problem, but occasionally an application servers won’t be expecting it and will throw an error. Just something to be aware of.
UPDATE thought I would try to answer your actual question as well. You will probably have to read the data into an intermediate byte buffer before passing the data to the BitmapFactory.
Unrelated, but remember to always call consumeContent() on the entity after use so that HttpClient can reuse the connection.