2012-02-01 44 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,我会提醒您这是一项艰巨的挑战任务,但绝对是合理的。