从相机捕获图像并在活动中显示

新手上路,请多包涵

我想编写一个模块,单击按钮即可打开相机,我可以单击并捕获图像。如果我不喜欢该图像,我可以将其删除并单击另一张图像,然后选择该图像,它应该返回并在活动中显示该图像。

原文由 Harsha M V 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 566
2 个回答

这是一个示例活动,它将启动相机应用程序,然后检索图像并显示它。

 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);
        }
    }
}

请注意,相机应用程序本身使您能够查看/重新拍摄图像,一旦图像被接受,活动就会显示它。

这是上述活动使用的布局。它只是一个 LinearLayout,包含一个 ID 为 button1 的 Button 和一个 ID 为 imageview1 的 ImageView:

 <?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。

原文由 jengelsma 发布,翻译遵循 CC BY-SA 4.0 许可协议

2021年5月,JAVA

在处理了本文旁边描述的必要权限后,在清单中添加:

 <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();
        }
    }
}

@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);
}

和:

  @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        picturePath = savedInstanceState.getString("safar");
    }
 ....
}

原文由 CodeToLife 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题