由于我没有找到完整的答案来回答我的问题,所以我发布了我的解决方案。
1. 从相机获取照片
protected File pictureFromCamera;
protected Uri photoUri;
...
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
pictureFromCamera = generateFile();
if (pictureFromCamera != null)
{
String authority = BuildConfig.APPLICATION_ID + ".provider";
photoUri = FileProvider.getUriForFile(DermatoPhotoCollectionActivity.this, authority, pictureFromCamera);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(takePictureIntent, REQUEST_PHOTO_FROM_CAMERA);
}
}
2. 获取照片的方向
以下是获取方向的代码,它受到了this article的启发。请注意,这需要一个依赖项:
compile "com.android.support:exifinterface:27.1.1"
获取照片的方向取决于设备,可能无法在某些设备上工作(例如,在我的Xperia上运行良好,但在Android模拟器上不行)。
public static int getOrientation(Context context, Uri photoUri)
{
InputStream in = null;
int orientation = ExifInterface.ORIENTATION_NORMAL;
try
{
in = context.getContentResolver().openInputStream(photoUri);
if (in != null)
{
android.support.media.ExifInterface exifInterface = new android.support.media.ExifInterface(in);
orientation = exifInterface.getAttributeInt(android.support.media.ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return orientation;
}
3. 如有需要,旋转图片
我使用asyncTask来旋转照片
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
final String pathPhotoFromCamera = pictureFromCamera.getAbsolutePath();
final ProgressDialog progressDialog = createProgressDialog();
progressDialog.show();
int orientation = getOrientation(this, photoUri);
int rotationAngle = 0;
if (orientation != ExifInterface.ORIENTATION_NORMAL)
{
switch (orientation)
{
case ExifInterface.ORIENTATION_ROTATE_90:
rotationAngle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotationAngle = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotationAngle = 270;
break;
}
}
AsyncTaskRotatePicture.AsyncTaskParams params = new AsyncTaskRotatePicture.AsyncTaskParams(pathPhotoFromCamera, rotationAngle);
AsyncTaskRotatePicture taskRotatePicture = new AsyncTaskRotatePicture(new CallBack()
{
@Override
public void onPostExecute()
{
progressDialog.dismiss();
}
});
taskRotatePicture.execute(params);
}
}
4. 最后旋转照片的代码
该函数将覆盖原始照片。
public static void rotatePhoto(String photoFilePath, int rotationAngle)
{
Bitmap bm = BitmapFactory.decodeFile(photoFilePath);
Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
byte[] extractedBitmap = extractByteFromBitmap(Bitmap.createBitmap(bm, 0, 0, bm.getWidth() - 1, bm.getHeight() - 1, matrix, true));
saveBitmapOnSdcard(extractedBitmap, photoFilePath);
}