Remember a problem that the photo is rotated after taking a photo with the system camera

In a recent project to do custom albums, encountered such a problem: from millet 9 were pulled up above camera phone camera system, and then uploaded to the server above, it somehow found picture rotated 90 ° , this is not in line with the business side After careful analysis, it is found that after taking a photo, the photo saved locally by the system has been rotated

Therefore, to solve this problem, only after taking a picture, judge whether the picture is rotated, if so, rotate it back

To get the rotation information of the picture, you need to get the Exit information of the picture. It stores all the parameters of the picture. We can get this data through ExifInterface :

/**
 * 读取图片的旋转的角度
 *
 * @param path 图片路径
 *            
 * @return 图片的旋转角度
 */
private int getBitmapDegree(String path) {
    
    
    int degree = 0;//被旋转的角度
    try {
    
    
        // 从指定路径下读取图片,并获取其 Exif 信息
        ExifInterface exifInterface = new ExifInterface(path);
        // 获取图片的旋转信息
        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;
        default:
            break;
        }
    } catch (IOException ignore) {
    
    
    }
    return degree;
}

If the degree is not 0, then it shows the picture has been rotated to , then we need to go back rotation:

    /**
     * @param filePath 文件存储路径
     * @param degree 旋转角度
     * @param savePath 文件保管路径
     */
    private void rotateBitmapByDegree(String filePath, int degree, String savePath)  {
    
    
        try {
    
    
            Matrix matrix = new Matrix();
            // 根据旋转角度,生成旋转矩阵
            matrix.postRotate(degree);
            Bitmap bm = BitmapFactory.decodeFile(filePath);
            // 将原始图片按照旋转矩阵进行旋转,并得到新的图片
            final Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
            //将新的图片保管到本地
            bitmap.compress(CompressFormat.JPEG, 85, new FileOutputStream(savePath));
        } catch (FileNotFoundException ignore) {
    
    
        }
    }

Guess you like

Origin blog.csdn.net/f409031mn/article/details/110787421