如何在ImageView中显示来自相册的图片?

huangapple go评论141阅读模式
英文:

How to display an image from the Gallery in an ImageView?

问题

private void openCameraToTakePictureIntent() {
    // ... (Same code)
}

private void openGalleryIntent() {
    // ... (Same code)
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK && requestCode == 1) {
        // ... (Same code)
    } else if (resultCode == Activity.RESULT_OK && requestCode == 2) {
        // ... (Same code)
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_modify_picture);

    Intent intent = getIntent();
    String imageUri = intent.getStringExtra("USER_IMAGE");

    if (imageUri != null) {
        // ... (Same code)
    } else {
        // ... (Same code)
    }

    image = findViewById(R.id.picture);
    image.setImageURI(Uri.parse(imageUri));
}

Note: The provided code excerpts are unchanged and directly translated from the original text. If you have any further questions or need assistance, feel free to ask.

英文:

I created a button that lets the user choose between "Take picture with camera" and "Select picture from gallery".

When the picture is taken/chosen, I then display it in an ImageView of the next activity which I do by passing the URI of the file created to store the taken/selected picture.

It works as expected when the user takes a picture with his camera but when he selects an image from gallery, no image is shown in the next activity despite both intents (take a picture and select a picture) being coded the same.

My question(s): Why isn't the image displayed in the next activity ONLY when picked from the gallery ? Or how should I proceed to display it ?

Intent to open camera (working fine):

private void openCameraToTakePictureIntent() {
    Log.d(TAG, "Method for Intent Camera started");
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }

        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.emergence.pantherapp.fileprovider", photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

Intent to access gallery and pick an image:

private void openGalleryIntent() {
    Log.d(TAG, "Method for Intent Gallery started");
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);

    if (galleryIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }

        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.emergence.pantherapp.fileprovider", photoFile);
            galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(galleryIntent, PICK_IMAGE);
        }
    }
}

Then here's the onActivityResult: (currentPhotoPath is the absolute path of the file created to store the image)

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK && requestCode == 1) {
        Log.d(TAG, currentPhotoPath);

        Intent intent = new Intent(this, ModifyPictureActivity.class);
        intent.putExtra("USER_IMAGE", currentPhotoPath);
        startActivity(intent);
    } else if (resultCode == Activity.RESULT_OK && requestCode == 2) {
        Log.d(TAG, currentPhotoPath);

        Intent intent = new Intent(this, ModifyPictureActivity.class);
        intent.putExtra("USER_IMAGE", currentPhotoPath);
        startActivity(intent);
    }

}

Below is how the image is displayed in the following activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_modify_picture);

    Intent intent = getIntent();
    String imageUri = intent.getStringExtra("USER_IMAGE");

    if (imageUri != null) {
        Log.d(TAG, imageUri);
    } else {
        Log.d(TAG, "imageUri was null");
    }

    image = findViewById(R.id.picture);

    image.setImageURI(Uri.parse(imageUri));

}

I made sure to have the READ_EXTERNAL_STORAGE in the manifest and the xml layout is just set to "match_parent" for height and width but I can add them if it's relevant.

答案1

得分: 1

少数Intent操作使用EXTRA_OUTPUT。大多数情况下,这是一个ACTION_IMAGE_CAPTURE的事情。

更常见的是,用于获取内容的IntentACTION_PICKACTION_GET_CONTENTACTION_OPEN_DOCUMENTACTION_CREATE_DOCUMENTACTION_OPEN_DOCUMENT_TREE等)会在传递给onActivityResult()Intent中返回来自内容供应商的Uri。根据您的实现,可以使用data.getData()来获取该Uri

然后,您可以使用ContentResolveropenInputStream()来获取与Uri标识的内容关联的InputStream。在您的情况下,例如,您可以使用该InputStream将字节复制到FileOutputStream,从而创建自己的本地内容副本。

请注意,您只能短暂访问由Uri标识的内容

英文:

Few Intent actions use EXTRA_OUTPUT. Mostly, that is an ACTION_IMAGE_CAPTURE thing.

More typically, an Intent for getting a piece of content (ACTION_PICK, ACTION_GET_CONTENT, ACTION_OPEN_DOCUMENT, ACTION_CREATE_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE, etc.) return a Uri from the content supplier in the Intentdelivered toonActivityResult(). Given your implementation, that would be data.getData()to get thatUri`.

You can then use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. In your case, for example, you could use that InputStream to copy the bytes to a FileOutputStream to make your own local copy of the content.

Note that you only have short-term access to the content identified by the Uri.

huangapple
  • 本文由 发表于 2020年8月27日 19:18:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63614860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定