Android从按钮打开相机

Posted

技术标签:

【中文标题】Android从按钮打开相机【英文标题】:Android open camera from button 【发布时间】:2012-12-08 06:32:37 【问题描述】:

我希望这不是一个重复的问题,但我正在制作一个应用程序,我想要一个按钮来打开相机应用程序(单独的默认 android 相机)。我该怎么做呢?我知道有一个功能:

intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE)

我需要使用它吗?以及如何从 xml 文件中调用按钮?

我还需要担心存储该图片或视频,还是默认相机应用会处理这些问题?

【问题讨论】:

使用本教程***.com/questions/8543244/custom-camera-android 【参考方案1】:

您可以创建相机意图并将其称为 startActivityForResult(intent)。

Intent intent = new 
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent 
startActivityForResult(intent, 
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

【讨论】:

【参考方案2】:
public class camera_act extends AppCompatActivity 

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_act);
         ImageView imageView = findViewById(R.id.image);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,90);
    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
        super.onActivityResult(requestCode,resultCode,data);
       Bitmap bitmap = data.getExtras.get("imageKey");
       imageView.setBitmapImage(bitmap);
            
        
    

【讨论】:

【参考方案3】:

我创建了一个库,用于从相机或厨房中挑选图像并进行裁剪

试试这个,

ImagePro.Java

public class ImagePro

    public static String TAG = "ImagePro";
    Activity activity;
    Uri mImageCaptureUri;
    public static int CAMERA_CODE = 64;
    public static int GALLERY_CODE = 74;
    public static int CROPPING_CODE = 84;
    private final static int REQUEST_PERMISSION_REQ_CODE = 704;

    public ImagePro(Activity activity) 

        this.activity = activity;
        this.outPutFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) 

            ActivityCompat.requestPermissions(activity, new String[]Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_PERMISSION_REQ_CODE);
        
    

    private void LogToast(String message) 

        try 
            Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
         catch (Exception e) 
            e.printStackTrace();
        

        Log.d(TAG, message);
    

    private void Toast(String message) 

        try 
            Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
         catch (Exception e) 
            e.printStackTrace();
        
    

    private void Log(String message) 

        Log.d(TAG, message);
    

    /**
     * This function return captured image path
     *
     * @param requestCode on activity result requestCode
     * @param resultCode on activity result resultCode
     * @param intent on activity result intent
     * @return ImageDetails values
     */
    public ImageDetails getImagePath(int requestCode, int resultCode, Intent intent) 

        ImageDetails imageDetails = new ImageDetails();

        if(resultCode == Activity.RESULT_OK) 

            if(requestCode == CAMERA_CODE) 
                imageDetails.setUri(mImageCaptureUri);
                imageDetails.setPath(mImageCaptureUri.getPath());
                Bitmap bitmap = null;

                try 
                    bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), mImageCaptureUri);
                 catch (IOException e) 
                    LogToast(e.getMessage());
                    e.printStackTrace();
                
                imageDetails.setBitmap(bitmap);
                imageDetails.setFile(new File(mImageCaptureUri.getPath()));

             else if(requestCode == GALLERY_CODE) 

                Uri uri = intent.getData();

                imageDetails.setUri(uri);
                Bitmap bitmap = null;

                try 
                    bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
                 catch (IOException e) 
                    LogToast(e.getMessage());
                    e.printStackTrace();
                

                imageDetails.setBitmap(bitmap);
                imageDetails.setFile(new File(uri.getPath()));
                imageDetails.setPath(uri.getPath());

             else if(requestCode == CROPPING_CODE) 
                try 
                    if(outPutFile.exists())

                        imageDetails.setUri(Uri.fromFile(outPutFile));
                        imageDetails.setFile(outPutFile);
                        imageDetails.setPath(outPutFile.getPath());
                        Bitmap photo = decodeFile(outPutFile);
                        imageDetails.setBitmap(photo);
                    
                    else 
                        LogToast("Error while save image");
                    
                 catch (Exception e) 

                    e.printStackTrace();
                    LogToast(e.getMessage());
                
            

         else 
            LogToast("user cancelled.");
        

        return imageDetails;
    

    /**
     * Open image pick dialog.<br/>
     * CAMERA_CODE</br>
     * GALLERY_CODE
     */
    public void openImagePickOption() 

        final CharSequence[] items =  "Capture Photo", "Choose from Gallery", "Cancel" ;

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() 
            @Override
            public void onClick(DialogInterface dialog, int item) 

                if (items[item].equals("Capture Photo")) 

                    captureImage();

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

                    pickImage();

                 else if (items[item].equals("Cancel")) 
                    dialog.dismiss();
                
            
        );
        builder.show();
    

    /**
     * decode from file to bitmap
     * @param f file
     * @return Bitmap data
     */
    private Bitmap decodeFile(File f) 
        try 
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 512;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) 
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
         catch (FileNotFoundException e) 

            Log(e.getMessage());
        
        return null;
    

    /**
     * Capture image using camera <br/>
     * REQUEST_CODE = ImagePro.CAMERA_CODE
     */
    public void captureImage() 

        if(activity != null) 

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
            mImageCaptureUri = Uri.fromFile(f);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
            activity.startActivityForResult(intent, CAMERA_CODE);

         else 

            LogToast("Activity not assigned");
        
    

    /**
     * pick image from gallery
     */
    public void pickImage() 

        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        activity.startActivityForResult(i, GALLERY_CODE);
    

    /**
     * cropping the uri image
     * @param uri - open cropping dialog using the uri data
     */
    public void croppingImage(Uri uri) 

        CroppingIMG(uri);
    

    int CROP_IMG_X=512;
    int CROP_IMG_Y=512;

    public void croppingImage(Uri uri, int cropX, int cropY) 

        CROP_IMG_X = cropX;
        CROP_IMG_Y = cropY;

        CroppingIMG(uri);
    

    File outPutFile=null;

    private void CroppingIMG(Uri uri) 

        final ArrayList<CroppingOption> cropOptions = new ArrayList<>();

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");

        List<ResolveInfo> list = activity.getPackageManager().queryIntentActivities( intent, 0 );
        int size = list.size();
        if (size == 0) 
            LogToast("Can't find image croping app");
         else 
            intent.setData(uri);
            intent.putExtra("outputX", CROP_IMG_X);
            intent.putExtra("outputY", CROP_IMG_Y);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);

            //Create output file here
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));

            if (size == 1) 
                Intent i   = new Intent(intent);
                ResolveInfo res = list.get(0);

                i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                activity.startActivityForResult(i, CROPPING_CODE);
             else 
                for (ResolveInfo res : list) 
                    final CroppingOption co = new CroppingOption();

                    co.title = activity.getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                    co.icon = activity.getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                    co.appIntent = new Intent(intent);
                    co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                    cropOptions.add(co);
                

                CropingOptionAdapter adapter = new CropingOptionAdapter(activity.getApplicationContext(), cropOptions);

                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setTitle("Choose Cropping App");
                builder.setCancelable(false);
                builder.setAdapter( adapter, new DialogInterface.OnClickListener() 
                    public void onClick( DialogInterface dialog, int item ) 
                        activity.startActivityForResult( cropOptions.get(item).appIntent, CROPPING_CODE);
                    
                );

                builder.setOnCancelListener( new DialogInterface.OnCancelListener() 
                    @Override
                    public void onCancel( DialogInterface dialog ) 

                        if (mImageCaptureUri != null ) 
                            activity.getContentResolver().delete(mImageCaptureUri, null, null );
                            mImageCaptureUri = null;
                        
                    
                 );

                AlertDialog alert = builder.create();
                alert.show();
            
        
    

    /**
     * Capture image using camera<br/>
     * REQUEST_CODE = User defined code<br/>
     * <br/>
     * @param iRequestCode User defined code
     */
    public void captureImage(int iRequestCode) 

        CAMERA_CODE = iRequestCode;
        captureImage();
    

    /**
     * get path, bitmap, file and uri from image details object
     */
    public class ImageDetails 

        String path="";
        Bitmap bitmap=null;
        File file=null;
        Uri uri=null;

        public Uri getUri() 
            return uri;
        

        public void setUri(Uri uri) 
            this.uri = uri;
        

        public String getPath() 
            return path;
        

        public void setPath(String path) 
            this.path = path;
        

        public Bitmap getBitmap() 
            return bitmap;
        

        public void setBitmap(Bitmap bitmap) 
            this.bitmap = bitmap;
        

        public File getFile() 
            return file;
        

        public void setFile(File file) 
            this.file = file;
        
    

    /**
     * Created by DP on 7/12/2016.
     */
    public class CroppingOption 
        public CharSequence title;
        public Drawable icon;
        public Intent appIntent;
    

    public class CropingOptionAdapter extends ArrayAdapter 
        private ArrayList<CroppingOption> mOptions;
        private LayoutInflater mInflater;

        public CropingOptionAdapter(Context context, ArrayList<CroppingOption> options) 

            super(context, R.layout.croping_selector, options);
            mOptions  = options;
            mInflater = LayoutInflater.from(context);
        

        @Override
        public View getView(int position, View convertView, ViewGroup group) 
            if (convertView == null)
                convertView = mInflater.inflate(R.layout.croping_selector, null);

            CroppingOption item = mOptions.get(position);

            if (item != null) 
                ((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
                ((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);

                return convertView;
            

            return null;
        
    

MainActivity.java

ImagePro imagePro;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imagePro = new ImagePro(this);
    

    public void onClickUploadImageButton(View view) 

        imagePro.openImagePickOption();
    

onActivityResult

if(requestCode == CAMERA_CODE && resultCode == RESULT_OK) 

            imageDetails = imagePro.getImagePath(CAMERA_CODE, RESULT_OK, data);
            ivCrop.setImageBitmap(imageDetails.getBitmap());
//imageDetails.getPath(), imageDetails.getBitmap(), imageDetails.getUri(), imageDetails.getFile
        

【讨论】:

【参考方案4】:

以下代码完全符合您的要求

//在点击事件上使用这个意图

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent,CAMERA_REQUEST);

//上面的代码用在'on activity Result'中

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

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

    if (requestCode == CAMERA_REQUEST) 
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        image.setImageBitmap(photo);
    

【讨论】:

这将设置相机拍摄的图像的缩略图版本,并失去照片质量【参考方案5】:

对我来说,这工作得很好。

 Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 startActivity(intent);

并将此权限添加到 mainfest 文件:

<uses-permission android:name="android.permission.CAMERA">

它会打开相机,在捕获图像后,它会将图像保存到带有新图像集的图库中。

【讨论】:

【参考方案6】:
 Button b = (Button)findViewById(R.id.Button01);

    b.setOnClickListener(new OnClickListener() 
        public void onClick(View v) 
             Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
             startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
        
    );


protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    if (requestCode == CAMERA_PIC_REQUEST) 
          Bitmap image = (Bitmap) data.getExtras().get("data");
          ImageView imageview = (ImageView) findViewById(R.id.ImageView01); //sets imageview as the bitmap
          imageview.setImageBitmap(image);
    

【讨论】:

什么是 camera_pic_request ? @MuhammedFasil 是请求代码,您可以通过请求代码 startActivityforResult 并在调用 OnActivity 结果时返回相同的代码。在你的类中声明这样的代码private static final int CAMERA_PIC_REQUEST = 1337; 根据this,data.getExtras().get("data") 将得到只有一个缩略图 @soshial 你是对的。 data.getExtras().get("data") 返回缩略图并丢失图像质量...【参考方案7】:

你可以使用下面的代码

         Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                pic = new File(Environment.getExternalStorageDirectory(),
                        mApp.getPreference().getString(Common.u_id, "") + ".jpg");

                picUri = Uri.fromFile(pic);

                cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, picUri);

                cameraIntent.putExtra("return-data", true);
                startActivityForResult(cameraIntent, PHOTO);

【讨论】:

【参考方案8】:

要调用相机,您可以使用:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);

图像将自动保存在默认目录中。

并且你需要在你的 AndroidManifest.xml 中设置摄像头的权限:

<uses-permission android:name="android.permission.CAMERA"> </uses-permission>

【讨论】:

我不了解你,但在我的情况下,它可以在未经许可的情况下工作 当您通过意图启动图像捕获操作时,无需包含 CAMERA 权限。【参考方案9】:

我知道回复有点晚了,但是您可以使用以下语法,因为它对我很有效

Camera=(Button)findViewById(R.id.CameraID);
Camera.setOnClickListener(new OnClickListener() 

        @Override
        public void onClick(View v) 
            // TODO Auto-generated method stub
            Intent Intent3=new   Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
            startActivity(Intent3); 
        
    );

【讨论】:

【参考方案10】:

您可以创建一个相机意图并将其称为 startActivityForResult(intent)。

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

   // start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

【讨论】:

【参考方案11】:

您对 Intent 中使用的操作是正确的,但这不是您唯一需要做的事情。您还必须添加

startActivityForResult(intent, YOUR_REQUEST_CODE);

要完成所有操作并检索实际图片,您可以查看以下线程。

Android - Capture photo

【讨论】:

以上是关于Android从按钮打开相机的主要内容,如果未能解决你的问题,请参考以下文章

在android中单击相机后,无需按确定按钮即可从相机获取图像

Android - 如何防止按下音量或相机键时手机屏幕打开?

在android中单击按钮时相机启动

Android - 如何从相机捕获图像或从库中添加

Android : 将图库功能与相机捕捉相结合

Android:单击按钮时切换相机