使用意图打开相机

时间:2013-05-28 19:23:17

标签: android android-intent android-camera

我想使用intent Android 中打开camera

我使用了以下代码,但是当我按下button(其操作为onclick()功能时,该应用自行关闭。

 public void onclick(int actionCode){
     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
     startActivityForResult(takePictureIntent, actionCode);
} 
public static boolean isIntentAvailable(Context context, String action) { 
    final PackageManager packageManager = context.getPackageManager(); 
    final Intent intent = new Intent(action); 
    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); 
    return list.size() > 0;
}

如果有人可以帮助我。

7 个答案:

答案 0 :(得分:9)

File destination;
Uri selectedImage;
public static String selectedPath1 = "NONE";
private static final int PICK_Camera_IMAGE = 2;
private static final int SELECT_FILE1 = 1;
public static Bitmap bmpScale;
public static String imagePath;



    mcamera = (Button) findViewById(R.id.button1);
    mcamera.setOnClickListener(new OnClickListener() {

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

            String name = dateToString(new Date(), "yyyy-MM-dd-hh-mm-ss");
            destination = new File(Environment
                    .getExternalStorageDirectory(), name + ".jpg");

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(destination));
            startActivityForResult(intent, PICK_Camera_IMAGE);

        }
    });

    // ......................gallery_function..........//
    mgallery = (Button) findViewById(R.id.button2);
    mgallery.setOnClickListener(new OnClickListener() {

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

意图 // .........................图库功能................. //

    public void openGallery(int SELECT_FILE1) {

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(
            Intent.createChooser(intent, "Select file to upload "),
            SELECT_FILE1);

}

// ............意图.........

                // ..................
protected void onActivityResult(int requestCode, int resultCode,
        Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    Uri selectedImageUri = null;
    String filePath = null;
    switch (requestCode) {
    case SELECT_FILE1:
        if (resultCode == Activity.RESULT_OK) {
            selectedImage = imageReturnedIntent.getData();

            if (requestCode == SELECT_FILE1) {
                selectedPath1 = getPath(selectedImage);
                // mimagepath.setText(selectedPath1);
                // Toast.makeText(Camera.this, "" + selectedPath1 + "",
                // 500).show();

                if (selectedPath1 != null) {

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

                    options.inJustDecodeBounds = true;
                    // image path `String` where your image is located
                    BitmapFactory.decodeFile(selectedPath1, options);



                // Log.d("setpath ", "setpath " + selectedPath1);
                ;

            }
        }

        break;
    case PICK_Camera_IMAGE:
        if (resultCode == RESULT_OK) {

            try {
                in = new FileInputStream(destination);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            imagePath = destination.getAbsolutePath();

            // Toast.makeText(Camera.this, "" + imagePath +
            // "",Toast.LENGTH_LONG).show();

        break;

    }

}

答案 1 :(得分:4)

试试这段代码

public static final int CAMERA_PIC_REQUEST = 1;//firstly define this 



Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
                    startActivityForResult(photo, CAMERA_PIC_REQUEST);

答案 2 :(得分:2)

传递给“点击后”方法的参数类型为View而不是int

根据this教程,您的onClick方法应如下所示:

public void onclick( View v ){
     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
     startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST);
}

CAMERA_PIC_REQUEST定义为(尽管我不太确定为什么你需要在应用程序中静态硬编码这个值):

private static final int CAMERA_PIC_REQUEST = 1337;  


更新

CAMERA_PIC_REQUEST用于唯一标识返回onActivityResult的结果。多个startActivityForResult请求可能一次未完成。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_PIC_REQUEST) { 
        if (resultCode == RESULT_OK) {
            tv.setText("Got picture!");
            imageData = (Bitmap) data.getExtras().get("data"); 
            ImageView image = (ImageView) findViewById(R.id.imageView1);
            image.setImageBitmap(imageData);
        } else if (resultCode == RESULT_CANCELED){
            tv.setText("Cancelled");
        }
    }  
} 

答案 3 :(得分:1)

我知道这个问题陈旧并回答,但对于那些问如何获取图像文件的人? 继承了解决方案。

String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera";

File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles()

String ImagePath = files[ file.files-1 ].getAbsolutePath();

Bitmap bmp = BitmapFactory.decodeFile(pathName); 
ivImage.setImageBitmap( bmp );

此外,您不需要在清单文件中添加相机权限。

如果这有助于你

,请进行投票

-Happy Codings ..

答案 4 :(得分:1)

从Android应用中启动相机非常简单: 只需在 onClick 方法

中编写两行代码
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
startActivityForResult(intent, CAMERA_PIC_REQUEST );

在班级中添加一个常量字段(您可以使用任意随机数而不是7)

private int CAMERA_PIC_REQUEST = 7;

答案 5 :(得分:0)

请看一下这段代码,这对我来说很好用

//define the file-name to save photo taken by Camera activity
fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
从拍摄相机拍摄图像时,

也会应用此方法读取图像。

    //handling intent responses
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK)
      try {
        if (bitmap != null) {bitmap.recycle();}

        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(imageUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        imageUriString = cursor.getString(column_index);

        getContentResolver().notifyChange(imageUri, null);
        ContentResolver cr = getContentResolver();

        try {
            bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);
            imageButtonPictureShop.setImageBitmap(bitmap);

// this.uploadImage();                 this.executeMultipartPost(); // this.uploadFile(imageUriString);             }             catch(例外e)             {                 Toast.makeText(this,“Failed to load”,Toast.LENGTH_SHORT).show();                 if(e.getMessage()!= null)Log.e(“Exception”,e.getMessage());                 其他Log.e(“例外”,“例外”);                 e.printStackTrace();             }

      } 
    catch (Exception e) 
    {
        if(e.getMessage() != null)Log.e("Exception"  , e.getMessage());
        else Log.e("Exception"  , "Exception");
        e.printStackTrace();
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

答案 6 :(得分:0)

经过大量研究,我找到了该解决方案。为了清楚起见,我为此问题创建了一个完整的应用程序,其目的是打开相机并单击照片并将图像设置为ImageView的ImageBitmap。在此问题中询问的代码从第二个块开始,即setView()方法位于onCreate()方法下面,之后我们具有onActivityResult()方法

这是该应用程序的演示。

Demonstration

下面我已经附加了MainActivity.java文件

package com.cr7.opencamera;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private Button buttonCaptureImageFromCamera;
    private Uri imageUri;
    private ImageView imageViewCameraImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Button that will open the camera
        buttonCaptureImageFromCamera = findViewById(R.id.buttonCaptureImageFromCamera);
        // ImageView that will store the image
        imageViewCameraImage = findViewById(R.id.imageViewCameraImage);
        askPermission();
    }

此处imageUri是全局变量,因此可以在onActivityResult()方法中使用

    // Sets OnClickListener for the button if storage permission is given
    private void setView() {
        buttonCaptureImageFromCamera.setOnClickListener(v -> {
            String fileName = "new-photo-name.jpg";
            // Create parameters for Intent with filename
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, fileName);
            values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera");
            imageUri =
                    getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            values);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, 1231);
        });
    }

这是onActivityResult方法。在这里,我使用了imageUri,即Uri类型的全局变量,该变量是在上述setView()方法中按钮的OnClickListener中初始化的。

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1231 && resultCode == Activity.RESULT_OK) {
            try {
                ContentResolver cr = getContentResolver();
                try {
                    // Creating a Bitmap with the image Captured
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(cr, imageUri);
                    // Setting the bitmap as the image of the
                    imageViewCameraImage.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IllegalArgumentException e) {
                if (e.getMessage() != null)
                    Log.e("Exception", e.getMessage());
                else
                    Log.e("Exception", "Exception");
                e.printStackTrace();
            }
        }
    }

剩余代码...


    // Asking user for storage permission
    public void askPermission() {
        // Checking if the permissions are not granted.
        if (
                ContextCompat.checkSelfPermission(
                        this,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(
                                this,
                                android.Manifest.permission.READ_EXTERNAL_STORAGE
                        ) != PackageManager.PERMISSION_GRANTED
        ) {
            // If not granted requesting Read and  Write storage
            ActivityCompat.requestPermissions(this, /*You can ask for multiple request by adding
            more permissions to the string*/new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE}, 60);
        } else {
            // If permissions are granted we proceed by setting an OnClickListener for the button
            // which helps the user pick the image
            setView();
        }
    }

    // This method is called after the permissions have been asked i.e. the dialog that says
    // allow or deny
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Now by default we assume that the permission has not been granted
        boolean allPermissionsGranted = false;
        // Now we check if the permission was granted
        if ( requestCode == 60 && grantResults.length > 0) {
            // If all the permissions are granted allPermissionsGranted is set to true else false
            allPermissionsGranted = grantResults[0] == PackageManager.PERMISSION_GRANTED
                    &&
                    grantResults[1] == PackageManager.PERMISSION_GRANTED;
        }
        // If permissions are granted we call the setView Method which prompts the user to pick
        // an Image either by the clicking it now or picking from the gallery
        if ( allPermissionsGranted ) {
            setView();
        }
    }
}

这些代码块是按顺序排列的,即,如果合并所有这些代码块,则会获得完整的MainActivity.java类。

如果您想实施此应用,则需要使用ID为“ imageViewCameraImage”的ImageView和ID为“ buttonCaptureImageFromCamera”的按钮创建一个布局文件。

希望这会有所帮助。我知道这很长,并且通过编写此代码来使它更长。 问候, 乔尔