将图片从URI复制到文件时,图片旋转90度

时间:2015-11-04 07:16:07

标签: java android image uri

我试图将图片从URI复制到文件路径。然后我从路径中读取了图片,但是我得到的图片向下旋转了90度。以下是我的功能。有人可以提供帮助吗?

public boolean copyPicture(Context context, Uri source, String dest) {
    boolean result = false;
    int bytesum = 0;
    int byteread = 0;
    File destFile = new File(dest);
    String scheme = source.getScheme();
    if (ContentResolver.SCHEME_CONTENT.equals(scheme)
            || ContentResolver.SCHEME_FILE.equals(scheme)) {
        InputStream inStream = null;
        try {
            inStream = context.getContentResolver().openInputStream(source);
            if (!destFile.exists()) {
                result = destFile.createNewFile();
            }
            if (result) {
                FileOutputStream fs = new FileOutputStream(dest);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.flush();
                fs.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
    }
    return result;
}

1 个答案:

答案 0 :(得分:1)

EXIF INTERFACE 就是答案。它允许您从图像文件中读取指定的属性。

Bitmap  bitmap = BitmapFactory.decodeFile(path, options);
                 try {

                        ExifInterface exif = new ExifInterface(path);
                        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

                        int angle = 0;

                        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                            angle = 90;
                        } 
                        else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                            angle = 180;
                        } 
                        else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                            angle = 270;
                        }
                        Matrix mat = new Matrix();
                        mat.postRotate(angle);
                        Bitmap correctBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);                 
                    bitmap=correctBmp;
                 }
                 catch(Exception e){

                 }