如何在库中保存位图?

时间:2017-01-10 20:56:27

标签: java android bitmap gallery

所以我有一个位图,在我编辑之后我希望用户可以保存它并在图库中查看它。我在谷歌搜索,发现很多想法,但我尝试过的都没有用。这是我的代码:

        ((ImageButton) findViewById(R.id. imageButton)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
            File myDir = new File(root + "/saved_images");
            myDir.mkdirs();
            Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            String fname = "Image-" + n + ".jpg";
            File file = new File(myDir, fname);
            if (file.exists())
                file.delete();
            try {
                FileOutputStream out = new FileOutputStream(file);
                mutableBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }


            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(MainActivity7.this, new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });
        }
    });

那么什么是错的,或者您是否有任何其他解决方案如何在库中保存我的位图?

1 个答案:

答案 0 :(得分:0)

转到设置>应用程序和查找您的应用程序是否允许存储权限。如果没有,请允许并重试。