Tuesday 22 August 2017

Camera Image Rotate Uri If Required in android

Image captured using camera intent gets rotated on some devices on Android?




Most phone cameras are landscape, meaning if you take the photo in portrait, the resulting photos will be rotated 90 degrees. In this case, the camera software should populate the Exif data with the orientation that the photo should be viewed in.
Note that the below solution depends on the camera software/device manufacturer populating the Exit data, so it will work in most cases, but it is not a 100% reliable solution.













private  
Uri rotateImageIfRequired(Context context,Bitmap img, Uri selectedImage) { // Detect rotation int rotation = getRotation(context, selectedImage); if (rotation != 0) { Matrix matrix = new Matrix(); matrix.postRotate(rotation); Bitmap rotatedImg = Bitmap.createBitmap(img, 0,
          0, img.getWidth(), img.getHeight(), matrix, true);
        img.recycle();
        return getImageUri(context,rotatedImg);
    }
    else{
        return selectedImage;
    }
}

/** * Get the rotation of the last image added. 
* @param context 
* @param selectedImage 
* @return */private  int getRotation(Context context, Uri selectedImage) {

    int rotation = 0;
    ContentResolver content = context.getContentResolver();

    Cursor mediaCursor = content.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[] { "orientation", "date_added" },
            null, null, "date_added desc");

    if (mediaCursor != null && mediaCursor.getCount() != 0) {
        while(mediaCursor.moveToNext()){
            rotation = mediaCursor.getInt(0);
            break;
        }
    }
    mediaCursor.close();
    return rotation;
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(),
                           inImage, "Title", null);
    return Uri.parse(path);
}

No comments:

Post a Comment