android - 将图像保存到图库中

android - save an image into gallery

我正在尝试将图像保存到 android 图库中,但不幸的是,它没有显示。

我的图片回调如下:

Camera.PictureCallback mPicture = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFileDir = getDir("images", 0);

            if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
                Toast.makeText(getApplicationContext(), "Can't create directory to save image.",
                        Toast.LENGTH_LONG).show();
                return;

            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
            String date = dateFormat.format(new Date());
            String photoFile = "Picture_" + date + ".jpg";

            String filename = pictureFileDir.getPath() + File.separator + photoFile;

            File pictureFile = new File(filename);

            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
                Toast.makeText(getApplicationContext(), "New Image saved:" + photoFile,
                        Toast.LENGTH_LONG).show();

                //Insert image into gallery
                Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() + pictureFile.getPath());
                MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, photoFile , "My Image");
            } catch (Exception error) {
                Toast.makeText(getApplicationContext(), "Image could not be saved.",
                        Toast.LENGTH_LONG).show();
            }

            //...
        }
 };

我认为图像已正确保存在应用程序数据中,但未显示在图库中。

我的应用需要这两个权限:

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

不幸的是,这段代码仍然不起作用。有什么不对的吗?

简化不正确的文件路径。

Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() + pictureFile.getPath());

我需要

Bitmap bitmap = BitmapFactory.decodeFile(pictureFile.getPath());