我需要捕获图像并将其显示在另一个活动中

时间:2016-05-29 13:20:26

标签: android camera

我有一个启动相机API的活动。 我想按下按钮(由id" cptr_1"命名)并拍摄照片并将其显示在另一个活动(PhotoPreview.class)中,我可以在其中添加照片效果。 我只需要代码:

    ImageButton capture_1 = (ImageButton)findViewById(R.id.cptr_1);
    capture_1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

然后如何将该图像传输到PhotoPreview.class

2 个答案:

答案 0 :(得分:1)

您可以使用设备的相机应用拍照。

所以当你点击:

    static final int ImageValue= 1;

    ImageButton capture_1 = (ImageButton)findViewById(R.id.cptr_1);
        capture_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent takepic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
               if (takepic.resolveActivity(getPackageManager()) != null) {
               startActivityForResult(takepic, ImageValue);
               }
            }
        });

完成捕获后,从相机应用程序中取回图像

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ImageValue && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
       }
}

然后将Bitmap发送到另一个活动。

在启动相机API的活动内写:

Intent intent = new Intent(this, PhotoPreview.class);
intent.putExtra("GetBitmap", bitmap);

PhotoPreview.class内写:

Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("GetBitmap");

此外,您可能需要将这些权限添加到Android Manifest

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

答案 1 :(得分:0)

您可以使用Intent拍照或使用自定义相机类 适用于camera intent

custom camera class

如果您已经拥有自定义相机类,则可以使用此代码`相机cam = Camera.open(cameraId);

capture_1.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        try {

            cam.takePicture(null, null, mPicture);


        } catch (Exception e) {

        }
    }
});


private PictureCallback mPicture = new PictureCallback() {

    public void onPictureTaken(final byte[] data, Camera camera) {

        try {

            File mediaFile = new File("file path/filename.jpg");

            FileOutputStream fos = new FileOutputStream(mediaFile);
            fos.write(data);
            fos.close();
            cam.startPreview();


        } catch (Exception e) {
        }
    }
};`
相关问题