使用相机拍摄照片时数据为空(Nexus 7)
Posted
技术标签:
【中文标题】使用相机拍摄照片时数据为空(Nexus 7)【英文标题】:Data is null when capturing photo with camera (Nexus 7) 【发布时间】:2015-05-17 02:28:15 【问题描述】:在某些手机上,当我使用相机将新照片加载到 ImageView 中时,我返回的数据为空。在其他手机上它工作正常。它适用于大多数 Kitkat 手机,但不适用于 Nexus 7 (4.4.2),谁知道还有什么。
适用于 HTC M8 (5.0.1)、HTC Desire X (4.1.1)、三星 Galaxy S4 (4.4.2)、三星 Galaxy S5 (5.0)。
我只共享用于在 Kitkat 上捕获图像的代码,但在处理位图转换并上传到服务器时,我会以不同的方式处理它们。
btn_camera.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View arg0)
Log.i("INTENT0", "PICK_FROM_CAMERA_KITKAT");
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentPicture,PICK_FROM_CAMERA_KITKAT);
dialog_newimg.dismiss();
);
@SuppressLint("NewApi")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
if (resultCode != RESULT_OK) return;
switch (requestCode)
case PICK_FROM_CAMERA_KITKAT:
if (data != null)
Log.i("data.getData()", data.getData() + ""); //null
[...many things..]
...
我阅读了一些类似的问题,并强调我不会以任何方式使用EXTRA_OUTPUT
。
有什么想法吗?
【问题讨论】:
你的意思是onActivityResult()
收到的Intent data
是null,还是data.getData()
返回null?
我的意思是 data.getData() 为空。
@erdomester 您找到解决方案了吗?我也遇到了这个问题。
我发布了一个答案。如果代码缺少任何内容,请告诉我。
【参考方案1】:
我做了这样的事情。实际上,关键是要以不同的方式处理 Uri:
if (data.getData() == null)
selectedImageUri = Uri.fromFile(imageFileForCamera_);
else
selectedImageUri = data.getData();
在此之后,使用辅助函数 getRealPathFromURI()
用于 Kitkat 上方和 getPath()
用于 Kitkat 下方以不同方式处理路径也很重要。
我在这里发布我的整个代码作为其他人的参考。该代码已经在数百名用户的各种设备中运行了 2 个月,无需强制关闭。
case PICK_FROM_CAMERA_COMPLETE:
if(resultCode == RESULT_OK)
if (data != null)
if (data.getData() == null)
selectedImageUri = Uri.fromFile(imageFileForCamera_);
else
selectedImageUri = data.getData();
else
selectedImageUri = Uri.fromFile(imageFileForCamera_);
complete_dialog.filename = getRealPathFromURI(selectedImageUri);
Bitmap bitmapSelectedImage;
try
bitmapSelectedImage = getSampleBitmapFromFile(getRealPathFromURI(selectedImageUri), 400, 400);
ExifInterface exifInterface = new ExifInterface(getRealPathFromURI(selectedImageUri));
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(orientation);
Matrix matrix = new Matrix();
if (rotationInDegrees != 0f)
matrix.preRotate(rotationInDegrees);
bitmapSelectedImage = Bitmap.createBitmap(bitmapSelectedImage, 0, 0, bitmapSelectedImage.getWidth(), bitmapSelectedImage.getHeight(), matrix, true);
Bitmap d = new BitmapDrawable(getApplicationContext().getResources(), bitmapSelectedImage).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
complete_dialog.iv_bucket2.setImageBitmap(scaled);
catch (FileNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
else if(resultCode == RESULT_CANCELED)
//DELETE FILE THAT WE CREATED FROM CAMERA
break;
case PICK_FROM_CAMERA_COMPLETE_KITKAT:
if(resultCode == RESULT_OK)
if (data != null)
if (data.getData() == null)
selectedImageUri = Uri.fromFile(imageFileForCamera_);
else
selectedImageUri = data.getData();
else
selectedImageUri = Uri.fromFile(imageFileForCamera_);
Bitmap bitmapSelectedImage2;
try
bitmapSelectedImage2 = getSampleBitmapFromFile(getPath(BucketProfileActivity.this, selectedImageUri), 400, 400);
ExifInterface exifInterface = new ExifInterface(getPath(BucketProfileActivity.this, selectedImageUri));
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(orientation);
Matrix matrix = new Matrix();
if (rotationInDegrees != 0f)
matrix.preRotate(rotationInDegrees);
bitmapSelectedImage2 = Bitmap.createBitmap(bitmapSelectedImage2, 0, 0, bitmapSelectedImage2.getWidth(), bitmapSelectedImage2.getHeight(), matrix, true);
Bitmap d = new BitmapDrawable(getApplicationContext().getResources(), bitmapSelectedImage2).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
complete_dialog.iv_bucket2.setImageBitmap(scaled);
catch (FileNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
else if(resultCode == RESULT_CANCELED)
//DELETE FILE THAT WE CREATED FROM CAMERA
break;
case LOAD_FROM_GALLERY_COMPLETE: //before KitKat
if(resultCode == RESULT_OK)
if (data != null)
complete_dialog.show();
Uri imageuri = data.getData();
complete_dialog.filename = getRealPathFromURI(imageuri);
Bitmap bitmapSelectedImage3;
try
bitmapSelectedImage3 = getSampleBitmapFromFile(getRealPathFromURI(imageuri), 400, 400);
ExifInterface exifInterface = new ExifInterface(getRealPathFromURI(imageuri));
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(orientation);
Matrix matrix = new Matrix();
if (rotationInDegrees != 0f)
matrix.preRotate(rotationInDegrees);
bitmapSelectedImage3 = Bitmap.createBitmap(bitmapSelectedImage3, 0, 0, bitmapSelectedImage3.getWidth(), bitmapSelectedImage3.getHeight(), matrix, true);
Bitmap d = new BitmapDrawable(getApplicationContext().getResources(), bitmapSelectedImage3).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
complete_dialog.iv_bucket2.setImageBitmap(scaled);
catch (FileNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
else if(resultCode == RESULT_CANCELED)
//DELETE FILE THAT WE CREATED FROM CAMERA
break;
case LOAD_FROM_GALLERY_KITKAT_COMPLETE: //after KitKat if(resultCode == RESULT_OK)
if (data != null)
complete_dialog.show();
Uri imageuri = data.getData();
complete_dialog.filename = getPath(BucketProfileActivity.this, imageuri);
Bitmap bitmapSelectedImage4;
try
bitmapSelectedImage4 = getSampleBitmapFromFile(getPath(BucketProfileActivity.this, imageuri), 400, 400);
ExifInterface exifInterface = new ExifInterface(getPath(BucketProfileActivity.this, imageuri));
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(orientation);
Matrix matrix = new Matrix();
if (rotationInDegrees != 0f)
matrix.preRotate(rotationInDegrees);
bitmapSelectedImage4 = Bitmap.createBitmap(bitmapSelectedImage4, 0, 0, bitmapSelectedImage4.getWidth(), bitmapSelectedImage4.getHeight(), matrix, true);
Bitmap d = new BitmapDrawable(getApplicationContext().getResources(), bitmapSelectedImage4).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
complete_dialog.iv_bucket2.setImageBitmap(scaled);
catch (FileNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
else if(resultCode == RESULT_CANCELED)
//DELETE FILE THAT WE CREATED FROM CAMERA
break;
辅助函数:
private String getRealPathFromURI(Uri contentURI)
String result;
Cursor cursor = getContentResolver().query(contentURI, null, "", null, null);
if (cursor == null) // Source is Dropbox or other similar local file path
result = contentURI.getPath();
else
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
//Log.i("IDX", idx + "");
// Log.i("RESULT", cursor.getString(idx) + "");
result = cursor.getString(idx); //force close here
cursor.close();
return result;
@TargetApi(Build.VERSION_CODES.KITKAT) @SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri)
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri))
// ExternalStorageProvider
if (isExternalStorageDocument(uri))
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type))
return Environment.getExternalStorageDirectory() + "/" + split[1];
// handle non-primary volumes
// DownloadsProvider
else if (isDownloadsDocument(uri))
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
// MediaProvider
else if (isMediaDocument(uri))
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type))
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
else if ("video".equals(type))
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
else if ("audio".equals(type))
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
final String selection = "_id=?";
final String[] selectionArgs = new String[]
split[1]
;
return getDataColumn(context, contentUri, selection, selectionArgs);
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme()))
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
// File
else if ("file".equalsIgnoreCase(uri.getScheme()))
return uri.getPath();
return null;
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs)
Cursor cursor = null;
final String column = "_data";
final String[] projection =
column
;
try
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst())
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
finally
if (cursor != null)
cursor.close();
return null;
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri)
return "com.android.externalstorage.documents".equals(uri.getAuthority());
【讨论】:
以上是关于使用相机拍摄照片时数据为空(Nexus 7)的主要内容,如果未能解决你的问题,请参考以下文章