Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. private static final int REQUIRED_IMAGE_WIDTH = 480;
  2.  
  3. Bitmap decodeScaledBitmap(Uri image) {
  4. Size initialSize = getImageSize(image);
  5.  
  6. int areaLimit = REQUIRED_IMAGE_WIDTH * REQUIRED_IMAGE_WIDTH;
  7. int targetWidth = (int) Math.sqrt((double) areaLimit * initialSize.width / initialSize.height);
  8. int targetHeight = (int) Math.sqrt((double) areaLimit * initialSize.height / initialSize.width);
  9. int sampleSize = calculateSampleSize(initialSize.width, REQUIRED_IMAGE_WIDTH);
  10.  
  11. BitmapFactory.Options options = new BitmapFactory.Options();
  12. options.inSampleSize = sampleSize;
  13. options.inDensity = Math.max(initialSize.width, initialSize.height);
  14. options.inTargetDensity = Math.max(targetWidth, targetHeight) * sampleSize;
  15.  
  16. try {
  17. InputStream input = getContentResolver().openInputStream(image);
  18. Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
  19. // reset density to display bitmap correctly
  20. if (bitmap != null)
  21. bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
  22. return bitmap;
  23. } catch (FileNotFoundException e) {
  24. e.printStackTrace();
  25. }
  26. return null;
  27. }
  28.  
  29. private Size getImageSize(Uri image) {
  30. InputStream input = null;
  31. try {
  32. input = getContentResolver().openInputStream(image);
  33. BitmapFactory.Options options = new BitmapFactory.Options();
  34. options.inJustDecodeBounds = true;
  35. BitmapFactory.decodeStream(input, null, options);
  36. return new Size(options.outWidth, options.outHeight);
  37. } catch (FileNotFoundException e) {
  38. e.printStackTrace();
  39. }
  40. return new Size(0, 0);
  41. }
  42.  
  43. private int calculateSampleSize(int currentWidth, int requiredWidth) {
  44. int inSampleSize = 1;
  45. if (currentWidth > requiredWidth) {
  46. int halfWidth = currentWidth / 2;
  47. // Calculate the largest inSampleSize value that is a power of 2 and keeps
  48. // width larger than the requested width
  49. while (halfWidth / inSampleSize >= requiredWidth) {
  50. inSampleSize *= 2;
  51. }
  52. }
  53. return inSampleSize;
  54. }
  55.  
  56. static final class Size {
  57. int width;
  58. int height;
  59.  
  60. public Size(int width, int height) {
  61. this.width = width;
  62. this.height = height;
  63. }
  64.  
  65. @NonNull
  66. @Override
  67. public String toString() {
  68. return "width: " + width + ", height: " + height;
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement