美好的一天。Android - 通過Camera Intent拍攝照片時確保照片方向被保留?
我建立一個Android應用程序,用戶可以在拍攝照片,然後會保存到某個文件路徑。我在使用相機意圖並將結果保存到自定義文件路徑以及在ImageView中將其顯示給用戶方面沒有任何問題。但是,當我在幾臺設備上測試時,我最近遇到了一個奇怪的行爲。
每當我走在人像照片中,我得到一個景觀效果。
這裏是我使用的代碼:
public void onTakePhoto(View view){
//camera stuff
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//folder stuff
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "folderHere");
imagesFolder.mkdirs();
File image = new File(imagesFolder, timeStamp + ".png");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
這將打開攝像頭,並採取1次射門。在1次拍攝後,用戶可以選擇重試拍照。我發現對於某些設備,即使拍攝照片肖像,輸出也會變成橫向。我已將活動的方向設置爲肖像。
什麼我迄今所做得到的結果,確定使用Exif文件旋轉,然後相應地旋轉它(在回答我有問題了一把這麼詳細)。但是,這裏的問題是,它需要一些時間,在我回到我在ImageView中看到它的活動之前,我會看到3-4秒的黑屏。
這是我使用的旋轉代碼:
文件是在字符串的文件路徑。
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, bounds);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(file, opts);
ExifInterface exif = null;
try {
exif = new ExifInterface(file);
} catch (IOException e) {
Log.e(TAG, "exception hit while making exif!", e);
}
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
int rotationAngle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;
Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth()/2, (float) bm.getHeight()/2);
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
FileOutputStream out = null;
try {
out = new FileOutputStream(imagePath);
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
Log.e(TAG, "exception hit while exporting!", e);
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
是否有一種可靠的方式來確保在保存照片時保存照相機的方向?如果相機是縱向的,那麼結果也應該是縱向的,相同的情況也適用於橫向。
我一直在環顧四周,但我有幸運。我能想到的解決方案可能是我們可以將某些東西與相機意圖一起傳遞,比如旋轉常量或其他東西,以便輸出不會混亂,並且我們獲得所需的方向。
任何幫助將不勝感激。謝謝。
我一直使用的所有Android相機總是將數據保存爲寬x高,而不是高x寬。這是EXIF數據的工作,爲您提供正確的方向。我認爲你的問題是,無論你用什麼代碼來旋轉圖像太慢 - 你能給我們一個樣本嗎? – npace
@npace:Android設備硬件/固件在方向上的行爲各不相同。有些設備與大多數Nexus設備一樣,可在拍攝照片時根據設備方向保存圖像。其他設備(如大多數三星設備)會將圖像保存爲橫向圖像,並根據拍攝照片時的設備方向設置EXIF標頭。應用程序可以嘗試對此進行規範化處理,但許多程序不會。 – CommonsWare
@npace更新了我的問題。 – Razgriz