Android如何在正面打开相机并拍照并将其存储在内存中

时间:2017-04-27 05:42:13

标签: android android-camera2

我的应用程序适用于后置摄像头,但不适用于前置摄像头。

我不确定应该做些什么更改,以便当用户按下按钮时,前置摄像头会打开?

我应该使用相机2 API吗?

到目前为止,这是我的代码:

ImageButton btnpic;
private static final int CAM_REQUEST=1313;

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

    if(requestCode == CAM_REQUEST){
        Bitmap bitmap = (Bitmap) data.getExtras().get("data");
        path = saveToInternalStorage(bitmap);
        btnpic.setImageBitmap(bitmap);
    }
}

class btnTakePhotoClicker implements  Button.OnClickListener{

    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
        startActivityForResult(intent, CAM_REQUEST);
    }
}

private String saveToInternalStorage(Bitmap bitmapImage){
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    // path to /data/data/yourapp/app_data/imageDir
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    File mypath=new File(directory,"profile.jpg");

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(mypath);
        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return directory.getAbsolutePath();
}

0 个答案:

没有答案