如何在Android Gallery中保存SD卡图像?

时间:2014-08-29 15:07:13

标签: android media sd-card save-image

我将图片保存到SD卡中,但它并没有出现在手机图库中。我可以在一个文件夹中看到已保存的图像,但它的文件夹并没有在图库中显示。

我的代码在这里,如何解决?

    img_icon.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {

            img_resim.buildDrawingCache();
            Bitmap bm = img_resim.getDrawingCache();

            OutputStream fOut = null;

            Uri outputFileUri;
            try {
                root = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "folder_name" + File.separator);
                root.mkdirs();
                File sdImageMainDirectory = new File(root, "myPicName.jpg");
                outputFileUri = Uri.fromFile(sdImageMainDirectory);
                fOut = new FileOutputStream(sdImageMainDirectory);
            } catch (Exception e) {
                Toast.makeText(context.getActivity(),
                        "Error occured. Please try again later.",
                        Toast.LENGTH_SHORT).show();
            }

            try {
                bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                fOut.flush();
                fOut.close();
            } catch (Exception e) {

            }

            context.getActivity()
                    .sendBroadcast(
                            new Intent(
                                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                    Uri.parse("file://"
                                            + Environment
                                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));

            return true;
        }
    });

    return rowView;
}

感谢您的帮助..

1 个答案:

答案 0 :(得分:1)

你的问题在于:

context.getActivity()
                .sendBroadcast(
                        new Intent(
                                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://"
                                        + Environment
                                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));

您要求Android重新索引Environment.DIRECTORY_PICTURES中的所有文件。

要求扫描整个目录树是浪费。在您的情况下,它更浪费,因为您没有将文件写入该目录。相反,您正在将该文件写入:

root = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");

因此,您的扫描将不会选择此文件,您正在写入外部存储上的某个随机位置。

您需要确定存储文件的正确位置,然后将一个文件编入索引。