Android:如何设置相机拍摄的图像的方向?

时间:2016-10-12 14:07:25

标签: android

我写了这段代码:

private File imageFile;

private void addButtonListener(){
    Button btn = (Button)findViewById(R.id.Button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            File pictureDictionary = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            imageFile = new File(pictureDictionary, "myImage");
            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
            startActivityForResult(i, 0);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == 0){
        Bitmap photo = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
        if(photo!=null) {
            ImageView view = (ImageView)findViewById(R.id.ImageView);
            view.setImageBitmap(photo);
        }
    }
}

当我在Galaxy s5上运行它并尝试拍摄肖像照片时,它会将照片旋转90度。 当我尝试拍摄风景照片时,应用程序会崩溃。

1 个答案:

答案 0 :(得分:0)

第一步:从图像中获取方向

private Matrix getOrientationMatrix(String path) {
    Matrix matrix = new Matrix();
    ExifInterface exif;
    try {
        exif = new ExifInterface(path);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
        case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
            matrix.setScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.setRotate(180);
            break;
        case ExifInterface.ORIENTATION_FLIP_VERTICAL:
            matrix.setRotate(180);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_TRANSPOSE:
            matrix.setRotate(90);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.setRotate(90);
            break;
        case ExifInterface.ORIENTATION_TRANSVERSE:
            matrix.setRotate(-90);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.setRotate(-90);
            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }


   return matrix;
}

第二步:旋转位图跟随方向

b = Bitmap.createBitmap(photo , 0, 0, outWidth, outHeight, getOrientationMatrix(path), true);