图库不会显示已保存的图像

时间:2018-08-20 16:35:34

标签: java android

我已经实现了一个代码,其中屏幕快照保存到Pictures目录下的文件夹中。画廊为什么不显示图像?

private static File getOutputMediaFile() {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "Solitude"); //change to your app name

        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("ss", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpg");


        return mediaFile;
    }

    private void takeScreenshot(){
        //Get screenshot
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File pictureFile = getOutputMediaFile();

        if (pictureFile == null){
            Log.d("ss", "error creating media file, check storage permission");
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            bitmap.recycle();
        } catch (FileNotFoundException e) {
            Log.d("ss", "File not found" + e.getMessage());
        }
        catch (IOException e) {
            Log.d("ss", "Error Accessing File" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

忽略此消息 绕过这个愚蠢的提示,要求我添加更多详细信息,因为我的帖子主要是代码。忽略此消息。

1 个答案:

答案 0 :(得分:0)

保存图像后,您需要扫描文件,以便它可以显示在图库中。

MediaScannerConnection.scanFile(context, new String[]{mediaFile.getAbsolutePath()},
    new String[]{"image/jpeg"}, null);