The solution to the photo being rotated after taking a photo on some Android phones - Rotate

On some Android phones (such as MT788, Note2), after using the Camera to take a photo, the obtained photo will be automatically rotated (90°, 180°, 270°), which is very unexpected. After careful analysis, because the rotation information is stored in the photo attribute, to solve this problem, in the onActivityResult method, after obtaining the photo data, read its rotation information. If it is not 0, it means that the photo has been After rotating, then use android.graphics.Matrix to rotate the photo back.

1. Read the rotation property of the image

/**
 * Read the rotation angle of the picture
 *
 * @param path
 * Image absolute path
 * @return the rotation angle of the image
 */
private int getBitmapDegree(String path) {
    int degree = 0;
    try {
        // Read the image from the specified path and get its EXIF ​​information
        ExifInterface exifInterface = new ExifInterface(path);
        // Get the rotation information of the image
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            degree = 90;
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            degree = 180;
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            degree = 270;
            break;
        }
    } catch (IOException e) {
        e.printStackTrace ();
    }
    return degree;
}

 2. Rotate the picture according to a certain angle

/**
 * Rotate the picture according to a certain angle
 *
 * @param bm
 * Images that need to be rotated
 * @param degree
 * Rotation angle
 * @return rotated image
 */
public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
    Bitmap returnBm = null;
  
    // Generate a rotation matrix based on the rotation angle
    Matrix matrix = new Matrix();
    matrix.postRotate(degree);
    try {
        // Rotate the original image according to the rotation matrix and get a new image
        returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
    } catch (OutOfMemoryError e) {
    }
    if (returnBm == null) {
        returnBm = bm;
    }
    if (bm != returnBm) {
        bm.recycle();
    }
    return returnBm;
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326697074&siteId=291194637
Recommended