Created
August 15, 2017 16:03
-
-
Save RowlandOti/3c4b4835c5580e8c367606322a4b1782 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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