我想写一个模块,在点击一个按钮,相机打开,我可以点击和捕捉图像。如果我不喜欢图像,我可以删除它,然后点击另一个图像,然后选择图像,它应该返回并在活动中显示该图像。
当前回答
你得好好研究一下相机。(我认为要做到你想要的,你必须保存当前的图像到你的应用程序,在那里做选择/删除,然后召回相机再试一次,而不是直接在相机内部重试。)
其他回答
下面是一个示例活动,它将启动相机应用程序,然后检索图像并显示它。
package edu.gvsu.cis.masl.camerademo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MyCameraActivity extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
请注意,相机应用程序本身提供了查看/重拍图像的功能,一旦图像被接受,活动就会显示它。
下面是上面的活动使用的布局。它只是一个包含id为button1的Button和id为imageview1的ImageView的LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/photo"></Button>
<ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>
</LinearLayout>
最后一个细节,一定要加上:
<uses-feature android:name="android.hardware.camera"></uses-feature>
如果摄像头是你应用功能的可选选项。请确保在权限中将require设置为false。像这样
<uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>
到你的manifest.xml。
正如其他人所讨论的,使用data. getextras ().get("data")只会得到低质量的缩略图。
解决方案是通过ACTION_IMAGE_CAPTURE意图传递一个位置,告诉相机在哪里存储全质量图像。
代码是Kotlin,不需要任何权限。
val f = File("${getExternalFilesDir(null)}/imgShot")
val photoURI = FileProvider.getUriForFile(this, "${packageName}.fileprovider", f)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
.apply { putExtra(MediaStore.EXTRA_OUTPUT, photoURI) }
startActivityForResult(intent, 1234)
然后对拍摄后的结果进行处理:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 1234 && resultCode == Activity.RESULT_OK) {
val bitmap = BitmapFactory.decodeFile(
File("${getExternalFilesDir(null)}/imgShot").toString()
)
// use imageView.setImageBitmap(bitmap) or whatever
}
}
您还需要像这里描述的那样添加一个外部FileProvider。AndroidManifest.xml:
<manifest>
<application>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provide_paths" />
</provider>
</application>
</manifest>
添加一个新文件app/src/main/res/xml/provide_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="." />
</paths>
最后,你应该用你自己的逻辑替换1234来跟踪请求代码(通常是一个包含RequestCode.CAPTURE_IMAGE等成员的枚举)
更新(2020)
谷歌已经添加了一个新的ActivityResultRegistry API,“让你处理startActivityForResult() + onActivityResult()以及requestPermissions() + onRequestPermissionsResult()流,而无需覆盖你的活动或片段中的方法,通过ActivityResultContract带来了增加的类型安全性,并为测试这些流提供了钩子”。
该API是在androidx中添加的。和androidx.fragment 1.3.0-alpha02。
所以你现在可以这样做:
val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { success: Boolean ->
if (success) {
// The image was saved into the given Uri -> do something with it
}
}
val imageUri: Uri = ...
button.setOnClickListener {
takePicture.launch(imageUri)
}
查看文档了解如何使用新的Activity结果API: https://developer.android.com/training/basics/intents/result#kotlin
有许多内置的activityresultcontract,允许您做不同的事情,如选择联系人,请求权限,拍照或拍摄视频。您可能对ActivityResultContracts感兴趣。拍摄上图。
注意androidx.fragment 1.3.0-alpha04弃用了Fragment上的startActivityForResult() + onActivityResult()和requestPermissions() + onRequestPermissionsResult() api。因此,从现在开始ActivityResultContracts似乎是一种新的做事方式。
原答案(2015)
我花了好几个小时才把它修好。代码几乎是从developer.android.com复制粘贴而来的,只有细微的区别。
在AndroidManifest.xml上请求此权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在你的Activity中,首先定义这个:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
然后在onClick中触发这个Intent:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.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
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
添加以下支持方法:
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 = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
然后接收结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使它工作的是MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)),这与developer.android.com的代码不同。原始代码给了我一个FileNotFoundException。
2021年5月,爪哇
在处理了本文旁边所述的必要权限后, 在manifest中添加:
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
....
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
....
其中${applicationId}是应用程序的包名,例如my.app.com。
在res - > xml > provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="my_images" path="Pictures" />
<external-path name="external_files" path="."/>
<files-path
name="files" path="." />
<external-cache-path
name="images" path="." />
</paths>
在活动:
private void onClickCaptureButton(View view) {
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) {
}
if(photoFile_!=null){
picturePath=photoFile_.getAbsolutePath();
}
// Continue only if the File was successfully created
if (photoFile_ != null) {
Uri photoURI_ = FileProvider.getUriForFile(this,
"my.app.com.fileprovider", photoFile_);
takePictureIntent_.putExtra(MediaStore.EXTRA_OUTPUT, photoURI_);
startActivityForResult(takePictureIntent_, REQUEST_IMAGE_CAPTURE);
}
}
}
还有三招:
...
private static String picturePath;
private static final int REQUEST_IMAGE_CAPTURE = 2;
...
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
picturePath= image_.getAbsolutePath();
return image_;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK
){
try {
File file_ = new File(picturePath);
Uri uri_ = FileProvider.getUriForFile(this,
"my.app.com.fileprovider", file_);
rasm.setImageURI(uri_);
} catch (/*IO*/Exception e) {
e.printStackTrace();
}
}
}
and
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("safar", picturePath);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
and:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
picturePath = savedInstanceState.getString("safar");
}
....
}
坏的质量
根据我的经验,如果我们使用
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, RESULT_ADD_PHOTO);
和处理onActivityResult()
Bitmap thumbnail= (Bitmap) data.getExtras().get("data");
它只会给你一个缩略图,当然有一个坏的质量。
不错的质量
您可以显示相机和保存您的图像文件在公共目录,例如在文档目录
在onClick()中使用这个
String imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) +
File.separator + "your_image_name.jpeg";
Intent i =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile = new File(imagePath );
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
startActivityForResult(i, RESULT_ADD_PHOTO);
在onActivityResult()中
Bitmap imageBitmap1 = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap imageBitmap = Bitmap.createBitmap(imageBitmap1, 0, 0, imageBitmap1.getWidth(), imageBitmap1.getHeight(), matrix, true);
binding.imageView.setImageBitmap(imageBitmap);
我使用postRotate(),因为在我的代码中,图像结果向左旋转,所以我需要将其旋转90
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 如何在Android工作室的外部库中添加一个jar ?
- GridLayout(不是GridView)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?