Android使用原始方向查看相机照片

时间:2016-02-28 09:22:41

标签: android camera operating-system

如果相机使用肖像拍摄照片,我需要知道如何以肖像方式查看照片。

public class PVCameraActivity extends AppCompatActivity {
    private ImageView imageview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pvcamera);
        imageview = (ImageView) findViewById(R.id.imageview);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"picture.jpg"));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Activity.DEFAULT_KEYS_DIALER) {
            imageview.setImageURI(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "picture.jpg")));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用ExifInterface检索图片方向,然后将其旋转到正确的方向:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == Activity.DEFAULT_KEYS_DIALER)
    {
        try
        {
            String filePath = new File(Environment.getExternalStorageDirectory(), "picture.jpg").getAbsolutePath();

            ExifInterface exifInterface = new ExifInterface(filePath);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

            float angle = 0;
            switch (orientation)
            {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    angle = 90f;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    angle = 180f;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    angle = 270f;
                    break;
            }

            Matrix matrix = new Matrix();
            matrix.postRotate(angle);

            Bitmap bitmap = BitmapFactory.decodeFile(filePath);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

            imageview.setImageBitmap(bitmap);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}