//rotating image based on uri / file
//note that uri is retrieved from contentresolver, and it returns rotate degree,
//while exif returns orientation code from 1 to 10
public static Bitmap adjust_bitmap_orientation(File file, Bitmap im) throws Exception {
//File imageFile = new File(cursor.getString(0));
if (! file.exists()) {
throw new FileNotFoundException("file missing: "+file.getAbsolutePath());
}
ExifInterface exif = new ExifInterface(
file.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
//int rotate = exifToDegrees(orientation);
Log.i(LOG_TAG, "photo-orientation-file path: "+file.getAbsolutePath());
Matrix matrix = exifMatrix(orientation);
if(matrix != null)
im = Bitmap.createBitmap(im, 0, 0, im.getWidth(), im.getHeight(), matrix, true);
return im;
}
public static Bitmap adjust_bitmap_orientation(Uri uri, Bitmap im) throws Exception {
//File imageFile = new File(cursor.getString(0));
Cursor cursor = AppActivityManager.getContentResolver().query(uri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.Images.ImageColumns.DATA }, null, null, null);
if (cursor.getCount() != 1) {
Log.e(LOG_TAG, "no orientation: "+uri.toString());
throw new Exception(("No orientation for: "+uri.toString()));
//return -1; //not found
}
cursor.moveToFirst();
int rotation = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION));
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
Log.i(LOG_TAG, "photo-orientation-uri: " + uri.toString());
if (rotation != 0) {
//cursor returned orientation is rotation degree!
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
Log.i(LOG_TAG, "has rotation: " + rotation + ", matrix: " + matrix.toString());
im = Bitmap.createBitmap(im, 0, 0, im.getWidth(), im.getHeight(), matrix, true);
}
return im;
}
public static Matrix exifMatrix(int orientation) throws Exception{
Matrix mtx = new Matrix();
Log.i(LOG_TAG, "exif: "+orientation);
switch (orientation) {
case ExifInterface.ORIENTATION_UNDEFINED:
//throw new Exception("Unable to get orientation");
Log.e(LOG_TAG, "exif orientation failed / no exif");
mtx = null;
break;
case ExifInterface.ORIENTATION_NORMAL:
mtx = null;
break;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
mtx.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
mtx.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
mtx.setRotate(180);
mtx.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
mtx.setRotate(90);
mtx.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
Log.i(LOG_TAG, "rotate 90");
mtx.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
mtx.setRotate(-90);
mtx.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
mtx.setRotate(-90);
break;
default:
return null;
}
return mtx;
}