更新于2018年8月29日:我发现这种方法在基于Android 8+的三星设备上不起作用。例如三星S8,我无法理解为什么这里又失效了。如果有人能够测试并查明原因,让我们一起尝试修复。
我找到了如何解决问题:这个方法非常愚蠢,对我来说也很困难。
第一步是获取活动结果。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
String _path = Environment.getExternalStorageDirectory() + File.separator + "TakenFromCamera.jpg";
String p1 = Environment.getExternalStorageDirectory().toString();
String fName = "/TakenFromCamera.jpg";
final int rotation = getImageOrientation(_path);
File file = resaveBitmap(p1, fName, rotation);
Bitmap mBitmap = BitmapFactory.decodeFile(_path);
在对文件进行更改之前,主要步骤是getImageOrientation
。
- 通过路径获取
getImageOrientation
- 重新保存文件(如果需要发送到服务器,如果只是预览,则可以跳过此步骤)
- 从文件中获取正确的位图
仅进行1和3步即可进行预览,并使用此函数-旋转位图。
private Bitmap checkRotationFromCamera(Bitmap bitmap, String pathToFile, int rotate) {
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return rotatedBitmap;
}
获取图片的方向
public static int getImageOrientation(String imagePath) {
int rotate = 0;
try {
ExifInterface exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return rotate;
}
如果需要的话,可以重新保存位图。
private File resaveBitmap(String path, String filename, int rotation) {
String extStorageDirectory = path;
OutputStream outStream = null;
File file = new File(filename);
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename);
}
try {
Bitmap bitmap = BitmapFactory.decodeFile(path + filename);
bitmap = checkRotationFromCamera(bitmap, path + filename, rotation);
bitmap = Bitmap.createScaledBitmap(bitmap, (int) ((float) bitmap.getWidth() * 0.3f), (int) ((float) bitmap.getHeight() * 0.3f), false);
bitmap = Utils.getCircleImage(bitmap);
outStream = new FileOutputStream(path + filename);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}