不能意图onActivityresult

时间:2019-03-14 05:34:34

标签: java android

private static final int CAMERA_REQUEST = 1337;
private void showCamera() {
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.putExtra("category", "camera");
    startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

我使用此代码从相机中拾取图像。这是我的活动结果

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST ) {
        filePath = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);
            Toast.makeText(this, data.getDataString(), Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    else if (requestCode == CAMERA_REQUEST) {
        filePath = data.getData();
            Log.i("hello", "REQUEST cALL");
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);

            } catch (Exception e) {
                Log.i("hello", "Exception" + e.getMessage());
            }
    }

相机很好。我可以捕捉到它

但是为什么imageview无法从相机中拾取照片?

但是如果我从存储中选择imageview可以更改图像。 可以看到错误的代码吗?

3 个答案:

答案 0 :(得分:0)

data.getData();

这没有给您filepath的捕获图像

您可以关注这个

Getting path of captured image in Android using camera intent

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  

        Bitmap photo = (Bitmap) data.getExtras().get("data"); 

       //get the URI of the bitmap from camera result
        Uri uri = getImageUri(getApplicationContext(), photo);


       // convert the URI to its real file path.
        String filePath = getRealPathFromURI(uri);

}

此方法获取位图的URI,可用于将其转换为文件路径

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

此方法将URI转换为文件路径

public String getRealPathFromURI(Uri uri) {
    String path = "";
    if (getContentResolver() != null) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            path = cursor.getString(idx);
            cursor.close();
        }
    }
    return path;
}

答案 1 :(得分:0)

尝试一下,希望对您有所帮助。

 if (requestCode == CAMERA_REQUEST) {   
        Bitmap bitmap= (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(bitmap);  
  }  

答案 2 :(得分:0)

要使用图像文件路径,您必须执行以下操作

1)编写一种创建图像文件的方法

String currentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
    imageFileName,  /* prefix */
    ".jpg",         /* suffix */
    storageDir      /* directory */
);

 // Save a file: path for use with ACTION_VIEW intents
  currentPhotoPath = image.getAbsolutePath();
  return image;
}

2)呼叫摄像机意图

private void showCamera() {
  Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

    File photoFile = null;
    try {
        photoFile = createImageFile();
    } catch (IOException ex) {
        // Error occurred while creating the File

    }
    // Continue only if the File was successfully created
    if (photoFile != null) {
        Uri photoURI = FileProvider.getUriForFile(this,
                                              "com.example.android.fileprovider",
                                              photoFile);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
    }
  }
}

3)现在,您需要配置FileProvider。在您的应用清单中,将提供程序添加到您的应用中:

<application>
 ...
 <provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths"></meta-data>
 </provider>
 ...
</application>

4)创建资源文件res/xml/file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
  <paths xmlns:android="http://schemas.android.com/apk/res/android">
 <external-path name="my_images" 
   path="Android/data/com.example.package.name/files/Pictures" />
</paths>

注意:请确保将com.example.package.name替换为应用程序的实际包名称。

5)获取imageFilePath

if (requestCode == CAMERA_REQUEST) {   
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), currentPhotoPath);
       imageView.setImageBitmap(bitmap); 
      // or you can use Glide to show image
      Glide.with(this).load(currentPhotoPath).into(imageView);
  }

希望它能按预期工作。有关详细信息,请参见google Official documents