チェロキー Web サーバーから画像を表示するアプリを作成したいと考えています。次のコードで画像をダウンロードします。
@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;
}
}
これは機能しますが、ダウンロードする必要がある画像が非常に大きい (数メガバイト) ため、ユーザーが何かを表示できるようになるまでに時間がかかります。
画像全体を読み込んでいるときに、画像の低解像度のプレビューを表示したい (他の Web ブラウザーと同じように)。どうやってやるの?BitmapFactory は、デコード前に完全にダウンロードされる、完全にロードされたファイルまたはストリームのみを受け入れるようです。
サーバーには高解像度の画像のみがあります。ダウンロード中に既にダウンロードした画像をすべて表示して、完全にダウンロードされる前に画像 (の一部) を表示したいだけです。そうすれば、ユーザーは、これが探していた画像ではないことがわかったらすぐにダウンロードを中止できます。