使用相机拍摄照片时数据为空(Nexus 7)

时间:2015-03-14 17:33:00

标签: android-camera android-camera-intent

在某些手机上,当我使用相机将新照片加载到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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我做了这样的事。实际上关键是以不同的方式处理Uri:

if (data.getData() == null) {
      selectedImageUri = Uri.fromFile(imageFileForCamera_);  
} else {
      selectedImageUri = data.getData();
}

在此之后,对于Kitkat以上的辅助函数getRealPathFromURI()和Kitkat以下的getPath()处理路径也很重要。

我在这里发布我的整个代码作为其他人的参考。这段代码已经在数百名用户的各种设备上工作了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());
}