Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static final int REQUIRED_IMAGE_WIDTH = 480;
- Bitmap decodeScaledBitmap(Uri image) {
- Size initialSize = getImageSize(image);
- int areaLimit = REQUIRED_IMAGE_WIDTH * REQUIRED_IMAGE_WIDTH;
- int targetWidth = (int) Math.sqrt((double) areaLimit * initialSize.width / initialSize.height);
- int targetHeight = (int) Math.sqrt((double) areaLimit * initialSize.height / initialSize.width);
- int sampleSize = calculateSampleSize(initialSize.width, REQUIRED_IMAGE_WIDTH);
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inSampleSize = sampleSize;
- options.inDensity = Math.max(initialSize.width, initialSize.height);
- options.inTargetDensity = Math.max(targetWidth, targetHeight) * sampleSize;
- try {
- InputStream input = getContentResolver().openInputStream(image);
- Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
- // reset density to display bitmap correctly
- if (bitmap != null)
- bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
- return bitmap;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- return null;
- }
- private Size getImageSize(Uri image) {
- InputStream input = null;
- try {
- input = getContentResolver().openInputStream(image);
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeStream(input, null, options);
- return new Size(options.outWidth, options.outHeight);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- return new Size(0, 0);
- }
- private int calculateSampleSize(int currentWidth, int requiredWidth) {
- int inSampleSize = 1;
- if (currentWidth > requiredWidth) {
- int halfWidth = currentWidth / 2;
- // Calculate the largest inSampleSize value that is a power of 2 and keeps
- // width larger than the requested width
- while (halfWidth / inSampleSize >= requiredWidth) {
- inSampleSize *= 2;
- }
- }
- return inSampleSize;
- }
- static final class Size {
- int width;
- int height;
- public Size(int width, int height) {
- this.width = width;
- this.height = height;
- }
- @NonNull
- @Override
- public String toString() {
- return "width: " + width + ", height: " + height;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement