我想写一个应用程序,显示来自切诺基网络服务器的图像。我用下面的代码下载图像:如何在Android上下载图片时显示图片预览?
@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;
}
}
这工作,但因为我需要下载的图像是相当大(多兆字节)需要一定的时间,直到用户可以看到任何东西。
我想在加载完整图像时显示图像的低分辨率预览(就像任何Webbrowser一样)。我怎样才能做到这一点? BitmapFactory似乎只接受完全加载的文件或在解码之前完全下载的流。
服务器上只有高分辨率图像。我只想显示下载时已下载的图像的所有内容,以便在图像完全下载之前显示(部分)图像。这样用户可以在他看到这不是他正在寻找的图片时立即终止下载。
不幸的是,我无法对服务器进行任何更改。 – hin 2013-02-23 16:47:39
Android不支持渐进式jpeg,但不确定是否可以让解码器解码部分。最有可能的方法是将原始图像保存到文件中,然后尝试执行并异步读取。这样,如果它是一个渐进的JPEG,你*可能会得到一个部分解码。但是,由于您无法更改服务器组件,因此无论您正在抓取哪个网站,都无法投放渐进式jpeg。可能更好地显示填充的进度指示器 – 2013-02-28 00:06:58