adjust Bitmap orientation - Android android.graphics

Android examples for android.graphics:Bitmap Operation

Description

adjust Bitmap orientation

Demo Code

import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;

public class Main {

  public static Bitmap adjustBitmap(String photopath) {
    Uri uri = Uri.parse(photopath);/* ww w .  j  a  v  a 2  s. c  om*/
    ExifInterface exif = null;
    try {
      exif = new ExifInterface(uri.getPath());
    } catch (IOException e) {
      e.printStackTrace();
    }
    int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    int rotationInDegrees = exifToDegrees(rotation);
    Matrix matrix = new Matrix();
    if (rotation != 0f) {
      matrix.preRotate(rotationInDegrees);
    }

    final BitmapFactory.Options options = new BitmapFactory.Options();

    options.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(photopath, options);
    options.inSampleSize = 3;
    options.inJustDecodeBounds = false;
    Bitmap yourSelectedImage = BitmapFactory.decodeFile(photopath, options);
    Bitmap adjustedBitmap = Bitmap.createBitmap(yourSelectedImage, 0, 0, yourSelectedImage.getWidth(),
        yourSelectedImage.getHeight(), matrix, true);
    return adjustedBitmap;
  }

  public static int exifToDegrees(int exifOrientation) {
    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
      return 90;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
      return 180;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
      return 270;
    }
    return 0;
  }

}

Related Tutorials