android - 从 Android 中的 url 加载图像,只有在小的时候

标签 android url bitmap httpclient httprequest

我正在使用 BitmapFactory.decodeStream 从 Android 中的 url 加载图像。我只想下载特定大小以下的图像,目前我正在使用 getContentLength 来检查这一点。

但是,有人告诉我 getContentLength 并不总是提供文件的大小,在这种情况下,我想在知道文件太大后立即停止下载大。执行此操作的正确方法是什么?

这是我当前的代码。如果 getContentLength 没有提供答案,我目前返回 null。

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;
}

最佳答案

1 。您也可以尝试这种方法。我相信它不会下载大文件的内容

HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();  
int length=connection.getContentLength(); 

if(length<max){  
  InputStream is = connection.getInputStream();  
  BitmapFactory.decodeStream(is,null,null);
}

这只是一个示例,您还可以添加检查 -1 和其他任何内容。 这种做法等同于你所做的。这只是您尝试的另一种选择。我只知道 HttpURLConnection 在您开始从流中读取内容之前不会获取内容。所以这段代码不会下载大图片。我真的不知道 HttpClient 是否也这样做。

2。为什么实际上你想跳过更大的文件。如果您担心解码期间内存不足,可以看看这个 Strange out of memory issue while loading an image to a Bitmap object .如果您应用 inSampleSize,您甚至可以下载大图像。对于较大的图像,延迟会更大,但内存消耗会很低。我在这里发布了我的 ListView 示例 Lazy load of images in ListView .它在 ListView 中显示图像。有不同大小的图像。图片不是很大,但无论如何。

关于android - 从 Android 中的 url 加载图像,只有在小的时候,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3328898/

相关文章:

android - 带有许多小图像的游戏中出现 OutOfMemoryError

c# - 如何设置背景图片 Xamarin Android

JavaScript - 从窗口获取 url 而不提交

php - 下载youtube文件时将eregi转换为正则表达式

c++ - 使用 GDI 创建 8bpp 位图并将其保存为文件

android - ImageView 中带圆角的位图

android - apk上传问题

java - 找不到 Robotium 存储库

android - 如何在Android上获取EditText的背景颜色

jquery - 在 Jquery 中使用获取 URL 哈希来更改 ID 的类别