捕获图像android后更新图库

时间:2017-04-11 09:14:41

标签: android image android-camera-intent

我尝试创建一个可以从相机捕获图像并根据图像路径显示结果的应用程序。处理捕获图像的按钮内部如下

btnImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                file = new File(Environment.getExternalStorageDirectory() + File.separator + "Nama_foto_" + waktu + ".jpg");

                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                intent.putExtra("return-data", true);

                getParentFragment().startActivityForResult(intent, CAPTURE_IMAGE);
            }catch (ActivityNotFoundException anfe){
                //display an error message
                String errorMessage = "Whoops - your device doesn't support capturing images!";
                Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    });

作为相机拍摄的回应我写下代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if(requestCode == CAPTURE_IMAGE) {

            performCrop();
        }
        else if(requestCode == PIC_CROP){
            //get the returned data
            Bundle extras = data.getExtras();
            //get the cropped bitmap
            Bitmap thePic = extras.getParcelable("data");

            picturePath = file.getAbsolutePath();

            try {
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thePic.compress(Bitmap.CompressFormat.JPEG, 80, bytes);

                file.createNewFile();
                FileOutputStream out = new FileOutputStream(file);
                out.write(bytes.toByteArray());
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //retrieve a reference to the ImageView
            //ImageView picView = (ImageView)findViewById(R.id.picture);
            //display the returned cropped image
        imgView.setImageBitmap(thePic);
        }

        try {

        }catch (Exception e) {
            Toast.makeText(getActivity(), "Maaf gagal mengambil foto.", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
}

}

在onCreateView外部声明的变量picturePath为空字符串。 问题是,每当我运行应用程序并捕获图像时。图像没有立即显示在画廊中,而是我需要重新运行应用程序(通过Android工作室)以查看图库中的图像。似乎oncreateview内部的某些内容会触发事件。但我仍然无法弄清楚是什么。

请帮助我解决问题。感谢

1 个答案:

答案 0 :(得分:2)

似乎你的问题应该以不同的方式改写: 这可以解决你的问题

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));

参考: How can I update the Android Gallery after a photo?