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


当前回答

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

其他回答

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

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。

以下是完整的代码:

package com.example.cameraa;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {




        Button btnTackPic;
        Uri photoPath;
        ImageView ivThumbnailPhoto;

        static int TAKE_PICTURE = 1;

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

            // Get reference to views

            btnTackPic = (Button) findViewById(R.id.bt1);
            ivThumbnailPhoto = (ImageView) findViewById(R.id.imageView1);




     btnTackPic.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, TAKE_PICTURE); 
            }




    });

        } 

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent intent) {


                if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {  
                    Bitmap photo = (Bitmap)intent.getExtras().get("data"); 
                   ivThumbnailPhoto.setImageBitmap(photo);
                ivThumbnailPhoto.setVisibility(View.VISIBLE);



            }
        }
}

记住也要为相机添加权限。

拍摄照片+从图库中选择:

        a = (ImageButton)findViewById(R.id.imageButton1);

        a.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                selectImage();

            }

        });
    }
    private File savebitmap(Bitmap bmp) {
      String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
      OutputStream outStream = null;
     // String temp = null;
        File file = new File(extStorageDirectory, "temp.png");
      if (file.exists()) {
       file.delete();
       file = new File(extStorageDirectory, "temp.png");

      }

      try {
       outStream = new FileOutputStream(file);
       bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
       outStream.flush();
       outStream.close();

      } catch (Exception e) {
       e.printStackTrace();
       return null;
      }
      return file;
     }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
     private void selectImage() {



            final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };



            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            builder.setTitle("Add Photo!");

            builder.setItems(options, new DialogInterface.OnClickListener() {

                @Override

                public void onClick(DialogInterface dialog, int item) {

                    if (options[item].equals("Take Photo"))

                    {

                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                        //pic = f;

                        startActivityForResult(intent, 1);


                    }

                    else if (options[item].equals("Choose from Gallery"))

                    {

                        Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                        startActivityForResult(intent, 2);



                    }

                    else if (options[item].equals("Cancel")) {

                        dialog.dismiss();

                    }

                }

            });

            builder.show();

        }



        @Override

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

            super.onActivityResult(requestCode, resultCode, data);

            if (resultCode == RESULT_OK) {

                if (requestCode == 1) {
                    //h=0;
                    File f = new File(Environment.getExternalStorageDirectory().toString());

                    for (File temp : f.listFiles()) {

                        if (temp.getName().equals("temp.jpg")) {

                            f = temp;
                            File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                           //pic = photo;
                            break;

                        }

                    }

                    try {

                        Bitmap bitmap;

                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();



                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),

                                bitmapOptions); 



                        a.setImageBitmap(bitmap);




                        String path = android.os.Environment

                                .getExternalStorageDirectory()

                                + File.separator

                                + "Phoenix" + File.separator + "default";
                        //p = path;

                        f.delete();

                        OutputStream outFile = null;

                        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");

                        try {

                            outFile = new FileOutputStream(file);

                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
    //pic=file;
                            outFile.flush();

                            outFile.close();


                        } catch (FileNotFoundException e) {

                            e.printStackTrace();

                        } catch (IOException e) {

                            e.printStackTrace();

                        } catch (Exception e) {

                            e.printStackTrace();

                        }

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                } else if (requestCode == 2) {



                    Uri selectedImage = data.getData();
                   // h=1;
    //imgui = selectedImage;
                    String[] filePath = { MediaStore.Images.Media.DATA };

                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);

                    c.moveToFirst();

                    int columnIndex = c.getColumnIndex(filePath[0]);

                    String picturePath = c.getString(columnIndex);

                    c.close();

                    Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));


                    Log.w("path of image from gallery......******************.........", picturePath+"");


                    a.setImageBitmap(thumbnail);

                }

            }

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

你可以使用此代码onClick监听器(你可以使用ImageView或按钮)

image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, 1);
            }
        }
    });

在imageView中显示

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        bitmap = (Bitmap) extras.get("data");
        image.setImageBitmap(bitmap);

    }
}

注意:将此插入舱单

<uses-feature android:name="android.hardware.camera" android:required="true" />