直接调用系统Camera

关键思路:

初始化 组件;

创建并启动拍照intent;

使用回调函数onActivityResult()处理图像。

 

 

关键代码:

初始化 组件:

takePicBtn = (Button) findViewById(R.id.buttonPicture);
takePicBtn.setOnClickListener(takePiClickListener);

takeVideoBtn = (Button) findViewById(R.id.buttonVideo);
takeVideoBtn.setOnClickListener(takeVideoClickListener);


创建并启动拍照intent:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

private final OnClickListener takePiClickListener = new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            Log.d(LOG_TAG, "Take Picture Button Click");
            //创建新的intent—————— 利用系统自带的相机应用:拍照
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            //创建保存图片的文件—————— create a file to save the image
            fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

            // 此处这句intent的值设置关系到后面的onActivityResult中会进入那个分支,即关系到data是否为null,如果此处指定,则后来的data为null——180行代码
            // 设置图片文件的名称——————set the image file name
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            //启动图片捕获intent
            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }

    };

使用回调函数onActivityResult()处理图像:

// 如果是拍照
        if (CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE == requestCode)
        {
            Log.d(LOG_TAG, "CAPTURE_IMAGE");
                       
            if (RESULT_OK == resultCode)
            {
                
                Log.d(LOG_TAG, "RESULT_OK");

                if (data != null)
                {
                    // 没有指定特定存储路径的时候
                    Log.d(LOG_TAG,"data is NOT null, file on default position.");

                }
                
                else
                {

                    Log.d(LOG_TAG, "data IS null, file saved on target position.");
                                       
                    // Resize the full image to fit in out image view.
                   
                    // Decode the image file into a Bitmap sized to fill the View
                   
                    Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), factoryOptions);

                    imageView.setImageBitmap(bitmap);
                }
               
            }
            else if (resultCode == RESULT_CANCELED)
            {
                // User cancelled the image capture
            }
            else
            {
                // Image capture failed, advise user
            }
        }

 

posted @ 2014-08-29 18:18  mmcmmc  阅读(219)  评论(0编辑  收藏  举报