问题
i want to write an app that displays images from a Cherokee webserver. I do download the images with the following code:
@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;
}
}
This works, but since the images I need to download are quite large (multiple megabytes) it takes some time until the user can see anything.
I want to show a low resolution preview of the image while loading the full image (just like any Webbrowser does). How can I do that? BitmapFactory seems to accept only completely loaded files or streams which are also downloaded completely before decoding.
There are only high resolution images on the Server. I just want to show everything of the image I already downloaded while downloading to show (parts of) the picture before it has been downloaded completely. That way the user can abort the download as soon as he sees that this is not the picture he was looking for.
回答1:
Well the easiest way to do this would be to just download two images. One that is small (let's say a few bytes) and then scale it up (it will look terrible but will give the notion of progress) while loading the larger image in the background. More than likely the small one will return first and you will be able to make it appear as if it is going from low res to high res.
回答2:
What about 2 AsyncTask? The first one download the small or low-res image and display it on ImageView after that the first AsyncTask call the second AsyncTask which download the full-res image.
来源:https://stackoverflow.com/questions/15042297/how-to-show-image-preview-while-downloading-it-on-android