2012-02-01 104 views
1

有人可以提供一些關於從相機捕獲「完整」圖像,然後將其作爲字節在「startActivityForResult」中轉換的代碼示例,也可以將其作爲位圖顯示在imageView中。任何幫助將被真正讚賞。Android - 相機

山姆

回答

2

處理相機有點棘手。這是我爲應用程序編寫的一段代碼。

private final int RECEIVE_CAMERA_PICTURE = 10; 
private Uri mCameraUri = null; 

mCameraUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues()); 
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraUri); 
mtimeCameraAcessed = System.currentTimeMillis(); 
startActivityForResult(cameraIntent, RECEIVE_CAMERA_PICTURE); 

現在要處理圖像捕獲,應在onActivityResult()方法中放置以下內容。您會注意到我已經進行檢查以獲取所捕獲圖像的方向。該值將有助於在通過ImageView的不同活動顯示圖像:

int orientation = -10; 

Intent displayCameraPictureIntent = new Intent(MainActivity.this, FilterActivity.class); 
displayCameraPictureIntent.setData(mCameraUri); 

String filePath = OtherUtils.getRealPathFromURI(mContext, mCameraUri); 
long fileSize = new File(filePath).length(); 

Cursor mediaCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Images.ImageColumns.ORIENTATION, MediaStore.MediaColumns.SIZE }, MediaStore.MediaColumns.DATE_ADDED + ">=?", new String[]{String.valueOf(mtimeCameraAcessed/1000 - 1)}, MediaStore.MediaColumns.DATE_ADDED + " desc"); 

//ensure that the app doesn't consume inappropriate data 
if (mediaCursor != null && mtimeCameraAcessed != 0 && mediaCursor.getCount() != 0) { 
    while(mediaCursor.moveToNext()){ 
     long size = mediaCursor.getLong(1); 
     //Extra check to make sure that we are getting the orientation from the proper file 
     if(size == fileSize){ 
       orientation = mediaCursor.getInt(0); 
       break; 
     } 
    } 
} 


displayCameraPictureIntent.putExtra("orientationValue", orientation); 
startActivity(displayCameraPictureIntent); 

現在,爲了展示形象,新的活動中:

private Bitmap imageBitmap = null; 

Uri imageUri = getIntent().getData(); 
shareImageUri = imageUri; 
try { 
imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri); 
} catch (Exception e) { 
// TODO Auto-generated catch block   
} 

// check whether image is in landscape or portrait mode 
if(getIntent().getIntExtra("orientationValue", 1) == 90) { 
    //image is in portrait. So, rotate the image by 90degrees so that it is displayed in portrait mode 
} 

//now, set the bitmap to the appropriate imageView. You might want to scale the bitmap, to avoid 
//memory issues. 

你也想檢查這鏈接,這說明了這段代碼的方向: Images taken with ACTION_IMAGE_CAPTURE always returns 1 for ExifInterface.TAG_ORIENTATION on some newer devices

請讓我知道,如果您有任何其他問題或疑慮。相反,如果您想使用Camera api,我會提醒您這是一項艱鉅的挑戰任務,但絕對是合理的。