Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.40 KB | None | 0 0
  1. public static Bitmap scaleImage(Context context, Uri photoUri) throws IOException {
  2.         InputStream is = context.getContentResolver().openInputStream(photoUri);
  3.         BitmapFactory.Options dbo = new BitmapFactory.Options();
  4.         dbo.inJustDecodeBounds = true;
  5.         BitmapFactory.decodeStream(is, null, dbo);
  6.         is.close();
  7.  
  8.         int rotatedWidth, rotatedHeight;
  9.         int orientation = getOrientation(context, photoUri);
  10.  
  11.         if (orientation == 90 || orientation == 270) {
  12.             rotatedWidth = dbo.outHeight;
  13.             rotatedHeight = dbo.outWidth;
  14.         } else {
  15.             rotatedWidth = dbo.outWidth;
  16.             rotatedHeight = dbo.outHeight;
  17.         }
  18.  
  19.         Bitmap srcBitmap;
  20.         is = context.getContentResolver().openInputStream(photoUri);
  21.         if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
  22.             float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
  23.             float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
  24.             float maxRatio = Math.max(widthRatio, heightRatio);
  25.  
  26.             // Create the bitmap from file
  27.             BitmapFactory.Options options = new BitmapFactory.Options();
  28.             options.inSampleSize = (int) maxRatio;
  29.             srcBitmap = BitmapFactory.decodeStream(is, null, options);
  30.         } else {
  31.             srcBitmap = BitmapFactory.decodeStream(is);
  32.         }
  33.         is.close();
  34.  
  35.         /*
  36.          * if the orientation is not 0 (or -1, which means we don't know), we
  37.          * have to do a rotation.
  38.          */
  39.         if (orientation > 0) {
  40.             Matrix matrix = new Matrix();
  41.             matrix.postRotate(orientation);
  42.  
  43.             srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
  44.         }
  45.  
  46.         String type = context.getContentResolver().getType(photoUri);
  47.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  48.         if (type.equals("image/png")) {
  49.             srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
  50.         } else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
  51.             srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
  52.         }
  53.         byte[] bMapArray = baos.toByteArray();
  54.         baos.close();
  55.         return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
  56.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement