Advertisement
Guest User

Untitled

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