相机拍照旋转

时间:2018-06-07 05:41:32

标签: java android camera android-camera

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo);

        cameraButton = findViewById(R.id.cameraButton);
        imageView = findViewById(R.id.imageView);

        cameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 0);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bitmap = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(bitmap);
    }
}

出于某种原因,上面的代码在拍摄后旋转图片。我尝试上传一张图片来说明我的意思。不确定StackOverflow是否添加了它

1 个答案:

答案 0 :(得分:2)

是的,你需要在EXIFINTERFACE

的帮助下进行管理

将以下代码写入onActivityResult()方法。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

String timeStamp = new SimpleDateFormat( "yyyyMMdd_HHmmss").format( new Date( ));
output_file_name = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + timeStamp + ".jpeg";

File pictureFile = new File(output_file_name);
if (pictureFile.exists()) {
    pictureFile.delete();
}

try {
    FileOutputStream fos = new FileOutputStream(pictureFile);

    Bitmap realImage = BitmapFactory.decodeByteArray(data, 0, data.length);

    ExifInterface exif=new ExifInterface(pictureFile.toString());

    Log.d("EXIF value", exif.getAttribute(ExifInterface.TAG_ORIENTATION));
    if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("6")){
        realImage= rotate(realImage, 90);
    } else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("8")){
        realImage= rotate(realImage, 270);
    } else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("3")){
        realImage= rotate(realImage, 180);
    } else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("0")){
        realImage= rotate(realImage, 90);
    }

    realImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);

    fos.close();

    imageView.setImageBitmap(realImage);

} catch (FileNotFoundException e) {
    Log.d("Info", "File not found: " + e.getMessage());
} catch (IOException e) {
    Log.d("TAG", "Error accessing file: " + e.getMessage());
}
}