Skip to content

Instantly share code, notes, and snippets.

@RowlandOti
Created August 15, 2017 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RowlandOti/3c4b4835c5580e8c367606322a4b1782 to your computer and use it in GitHub Desktop.
Save RowlandOti/3c4b4835c5580e8c367606322a4b1782 to your computer and use it in GitHub Desktop.
class BitmapDownloadTask extends AsyncTask<Uri, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private Uri data = null;
public BitmapDownloadTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
@Override
protected Bitmap doInBackground(Uri... params) {
data = params[0];
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(data.toString(),options);
options.inSampleSize= calculateInSampleSize(options,300,300);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(data.toString(),options);
}
// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment