Android编程中的注册照片问题

tyu7yeag  于 2023-01-15  发布在  Android
关注(0)|答案(1)|浏览(103)

我正在实现一个Android应用程序使用相机拍照,然后将其注册在External_storage\Android\data\com.abc.projectname.bf中。但打开相机后,即使我不捕捉,一个图像文件也会注册在目录中。我该如何解决这个问题,下面是代码:

public void onCapturePhoto(String fileName){
    //Intent to take photos

    File storageDirectory = requireActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    try {
        Log.d("#picName",fileName);
        File imageFile = File.createTempFile(fileName,".jpg",storageDirectory);

            currentPhotoPath = imageFile.getAbsolutePath();
            Uri imageUri= FileProvider.getUriForFile(requireActivity(),"com.ticanalyse.mheath.bf",imageFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent,1);
            Log.d("#image_length is ",String.valueOf(imageFile.length()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            //  imageView.setImageBitmap(imageBitmap);
//            File f = new File(currentPhotoPath);
////            Uri contentUri = Uri.fromFile(f);
//            Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);
//            //Convert bitmap to byteArray
//            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//            bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
//            byte[] byteArray = byteArrayOutputStream .toByteArray();
//            //Then convert to base64
//            encodedImage= Base64.encodeToString(byteArray, Base64.DEFAULT);
//            Log.d("#base64",encodedImage);

            //   setPic();

        }
    }
vmdwslir

vmdwslir1#

首先,从这一行获得imageFile对象:

File imageFile = File.createTempFile(fileName,".jpg",storageDirectory);

...在“活动”中声明为全局变量,如下所示...

public class XYZActivity extends AppCompatActivity {
    private File imageFile;
    //onCreate(), onCapturePhoto(), etc methods
}

然后在onCapturePhoto()中:

imageFile = File.createTempFile(fileName,".jpg",storageDirectory);

现在在onActivityResult()中,如果您确保没有拍摄/单击任何图像,则可以尝试删除临时文件,如下所示:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK) {
         //Your stuff...
    }
    else {
        //No photo was taken or clicked...
        //Thus, deleting the temporary file...
        if (file.exists()) {
            if (file.delete()) {
                Log.i("Process", "Deletion DONE!");
            }
        }
    }
}

如果我对问题的任何部分有不好的解释,请告诉我。

相关问题