英文:
How to start a new activity passing an image uri
问题
我有一个带有按钮的活动,点击按钮会打开一个对话框,允许选择“拍照”或“从图库选择图片”,代码如下:
private void showDialogToSelectAFile() {
MaterialAlertDialogBuilder dialog = new MaterialAlertDialogBuilder(this);
dialog.setTitle("选择文件或拍照")
.setMessage("选择其中一个选项")
.setNeutralButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 什么都不做
}
}).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
openCameraToTakePictureIntent();
}
}).setNegativeButton("从图库选择文件", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
openGalleryIntent();
}
}).show();
}
然后运行以下意图来执行所选操作:
private void openCameraToTakePictureIntent() {
Log.d(TAG, "启动相机意图的方法开始");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 确保有相机活动来处理意图
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// 创建图片应存储的文件
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// 创建文件时发生错误
}
// 仅在成功创建文件时继续
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.emergence.domain.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
现在,我想启动一个新的活动,该活动将显示图片并允许对该图片进行修改,所以我打算在 "onActivityResult" 中传递URI,但我不知道如何做。
目前为止,虽然不会崩溃,我可以选择一张图片或拍照,但当我这样做时,它只是回到活动,除了(希望)在文件中存储图像之外什么也不做。
我的问题:
有没有更好的方法在保持完整质量的同时将图像传递到新的活动?
如果没有,我如何传递此URI并在新的活动中检索图像?
我的图像实际上是否存储在我创建的文件中?
这是我的 "createImageFile" 函数,以防它有关:
private File createImageFile() throws IOException {
// 创建图像文件名
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* 前缀 */
".jpg", /* 后缀 */
storageDir /* 目录 */
);
// 保存文件路径,用于 ACTION_VIEW 意图
currentPhotoPath = image.getAbsolutePath();
return image;
}
谢谢你的帮助。
编辑:
我已更新 "onActivityResult" 如下:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1) {
Intent intent = new Intent(this, ModifyPictureActivity.class);
intent.putExtra(MediaStore.EXTRA_OUTPUT, currentPhotoPath);
startActivity(intent);
}
}
我创建了这个新的活动,它只有一个 ImageView,在其中我想显示图片,但我找不到正确的方法将图像设置到 Extras 中。目前我有这个:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_picture);
Intent intent = getIntent();
intent.getExtras();
image = findViewById(R.id.image);
image.setImageURI(???);
}
我应该尝试使用除了 "setImageURI" 之外的其他方法来设置图像吗?
英文:
I have an activity with a button that opens a dialog allowing to choose between Taking a picture or Selecting a picture from gallery coded like that:
private void showDialogToSelectAFile() {
MaterialAlertDialogBuilder dialog = new MaterialAlertDialogBuilder(this);
dialog.setTitle("Select a file or take a picture")
.setMessage("Choose one of the options")
.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//do nothing
}
}).setPositiveButton("Take a picture", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
openCameraToTakePictureIntent();
}
}).setNegativeButton("Select a file from your gallery", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
openGalleryIntent();
}
}).show();
}
Then it runs the following intent to do the selected action:
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
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.emergence.domain.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Now I want to start a new activity that will display the picture and allow modifications on this picture so I though I'd pass the URI in an "onActivityResult" but I can't figure out how to do it.
So far it doesn't crash, I can select an image or take a picture but of course when I do so, it only goes back to the activty doing nothing except hopefully storing the image in the file.
My questions:
Is there a better way to proceed to pass an image to a new activity while keeping it full quality ?
If not, how can I pass this URI and retrieve the image in the new activity ?
Is my image actually stored in the file I created ?
Here is my createImageFile function in case it's relevant:
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;
}
Thanks for your help
EDIT:
I have updated the onActivityResult as follow:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1) {
Intent intent = new Intent(this, ModifyPictureActivity.class);
intent.putExtra(MediaStore.EXTRA_OUTPUT, currentPhotoPath);
startActivity(intent);
}
I created this new activity that only has an ImageView in which I want to display the picture but I can't find the right method to set the image to the Extras. So far I have this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_picture);
Intent intent = getIntent();
intent.getExtras();
image = findViewById(R.id.image);
image.setImageURI(???);
}
Should I try to set the image with another method than "setImageURI"?
答案1
得分: 1
实际上,您有两个选项:
- 如果您想要一个小尺寸的图像,您可以通过解码位图在
onActivityResult
回调中获取它。 - 因为您正在传递带有
EXTRA_OUTPUT
键的URI,MediaStore
将文件保存到该位置。因此在onActivityResult
回调中,您只需检查消息是否为“ok”,并且请求代码是否对应,之后您可以通过使用传递给EXTRA_OUTPUT
键的URI从文件中读取。
英文:
Actually you have two options:
- If you want a small-sized image, you can get it in the
onActivityResult
callback via decoding the bitmap - Since you are passing in the uri, with the
EXTRA_OUTPUT
key,MediaStore
will save the file to that location. So in theonActivityResult
callback, you just check if the message isok
and the request code corresponds, after that you can read from the file with the URI you've passed in with theEXTRA_OUTPUT
key
答案2
得分: 0
在onActivityResult检查中,如果URI不为空,请将其传递给新的活动
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("uri", uri);
startActivity(intent);
然后在(你的新活动)中使用以下代码行来获取URI
Bitmap photo = BitmapFactory.decodeFile(intent.getStringExtra("uri"));
imageView.setImageBitmap(photo);
注意:将URI作为字符串传递。
英文:
in onActivtyResult check, if URI not null pass it to your new activity
Intent intent = Intent(this, your activity)
intent.putExtra("uri", uri)
startActivity(intent)
then in (your new activity) use these lines to get Uri
Bitmap photo= BitmapFactory.decodeFile(intent.getStringExtra("uri"))
imageView.setImageBitmap(photo)
NOTE: pass uri as string
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论