android - 将图像保存到图库中

时间:2015-01-29 00:58:09

标签: android image camera android-camera 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"/>

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

1 个答案:

答案 0 :(得分:0)

只是一个不正确的文件路径。

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

需要我

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