我在 AsynTask 中为创建的每个类从 Web 服务器抓取缩略图。对于这个特定问题,我在 ListView 中显示缩略图和一些文本属性。
问题是它非常慢。我考虑过在第一次需要时将每个图像保存到设备,然后每次都可以从数据库中提取它。我不确定这是否理想,因为图像可能会或可能不会在服务器上更新。在我看来,最好始终抓取动态图像,以防有新图像要抓取。
我想听听各位好心人的一些建议。
注意:我也尝试过在 ListView 适配器中获取图像,但是 1) 每次滚动 ListView 时它都会获取每张图像,并且 2) 它有令人难以置信的错误,因为随着每个图像的下载,我可以看到图像出现在错误的 ListView 项目中,然后它会在一段时间后神奇地自行纠正。这一点都不理想,所以我将代码移到了类中。
如果有任何建议,我将不胜感激。
这是类中图像的 setter/getter 。这在第一次下载图像后工作正常,但在初始运行期间效果不佳。
public Bitmap GetThumbnail_xlarge() throws Exception {
if(_thumbnail_xlarge == null ) {
if( _thumbnailBasePath != null) {
try {new DownloadImageTask(_thumbnail_xlarge).execute(_thumbnailBasePath + "/portrait_xlarge." + _thumbnailExtension); }
catch (Exception e) {} //TODO: The extension could be incorrect. Do nothing for now.
}
else{ throw new Exception("You must set the thumbnail path before getting the image"); }
}
return _thumbnail_xlarge;
}
并且,这是完成这项工作的类。请注意,这是图像属性所在类中的私有(private)类:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
Bitmap bmImage;
public DownloadImageTask(Bitmap bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) { _thumbnail_xlarge = result; }
}
目前我想不出任何其他可能相关的内容。如有必要,请向我询问更多信息,在此先感谢您!
最佳答案
将图像保存在本地以备后用非常有用。顺便说一句,这称为缓存。这很有用,因为您正在节省资源,并且可以减少使用大量资源的网络请求。
如果图像很大,您可以使用 WebP 格式。 WebP 是一种图像格式,它是“网络上图像的无损和有损压缩。WebP 无损图像比 PNG 小 26%。WebP 有损图像比同等 SSIM 索引的 JPEG 图像小 25-34% ” 您可以在此处找到有关 WebP 格式的更多信息:https://developers.google.com/speed/webp/?csw=1
此外,如果您想在 ListView 上顺利加载图像,则必须使用 ViewHolder 模式。更多信息在这里:http://developer.android.com/training/improving-layouts/smooth-scrolling.html#ViewHolder
关于java - 图片检索速度慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28099703/