简体   繁体   English

使用相机拍照并保存到手机库

[英]Use Camera to Take Photos and Save them to the Phone Gallery

I am new to Android Studio. 我是Android Studio的新手。 I want to capture photo with phone camera by clicking a button, then display the taken photo, and the photo will save automatically in the phone gallery. 我想通过单击一个按钮用手机摄像头捕获照片,然后显示所拍摄的照片,该照片将自动保存在电话库中。 I have found some online examples but the photo that I captured is not saved inside the gallery. 我找到了一些在线示例,但是我捕获的照片没有保存在图库中。 I already used the code below. 我已经使用了下面的代码。 May I get some help please? 我可以帮忙吗?

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.buttonTakePhoto:
            Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, CAMERA_PIC_REQUEST);
            break;
    }
} 

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.imageView);
        imageview.setImageBitmap(image);
    }
}

To Take image by using camera intent and store it in gallery use this and you will get result in onActivityResult 要使用相机意图拍摄图像并将其存储在图库中,请使用此方法,您将在onActivityResult获得结果

    private void takeImageFromCamera() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File exportDir = new File(Environment.getExternalStorageDirectory(), "TempFolder");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        } else {
            exportDir.delete();
        }
        File mTempCameraPhotoFile = new File(exportDir, "/" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg");
        Log.d("TAG", "/" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg");
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempCameraPhotoFile));


        startActivityForResult(takePictureIntent, Config.CAMERA_PIC_REQUEST);

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM