【发布时间】:2013-02-23 15:43:31
【问题描述】:
我想编写一个显示来自 Cherokee 网络服务器的图像的应用程序。我确实使用以下代码下载图像:
@Override
protected Bitmap doInBackground(URL... params) {
URL urlToDownload = params[0];
String downloadFileName = urlToDownload.getFile();
downloadFile = new File(applicationContext.getCacheDir(), downloadFileName);
new File(downloadFile.getParent()).mkdirs(); // create all necessary folders
// download the file if it is not already cached
if (!downloadFile.exists()) {
try {
URLConnection cn = urlToDownload.openConnection();
cn.connect();
cn.setReadTimeout(5000);
cn.setConnectTimeout(5000);
InputStream stream = cn.getInputStream();
FileOutputStream out = new FileOutputStream(downloadFile);
byte buf[] = new byte[16384];
int numread = 0;
do {
numread = stream.read(buf);
if (numread <= 0) break;
out.write(buf, 0, numread);
} while (numread > 0);
out.close();
} catch (FileNotFoundException e) {
MLog.e(e);
} catch (IOException e) {
MLog.e(e);
} catch (Exception e) {
MLog.e(e);
}
}
if (downloadFile.exists()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 16;
return BitmapFactory.decodeFile(downloadFile.getAbsolutePath(), options);
} else {
return null;
}
}
这可行,但由于我需要下载的图像非常大(数兆字节),用户需要一些时间才能看到任何内容。
我想在加载完整图像时显示图像的低分辨率预览(就像任何网络浏览器一样)。我怎样才能做到这一点? BitmapFactory 似乎只接受完全加载的文件或在解码之前也完全下载的流。
服务器上只有高分辨率图像。我只想在下载时显示我已经下载的图像的所有内容,以便在完全下载之前显示(部分)图片。这样一来,用户可以在看到这不是他要查找的图片时立即中止下载。
【问题讨论】:
标签: android image preview download bitmapfactory