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

标签 java android

我已经实现了一个代码,其中截图被保存到图片目录下的文件夹中。为什么图库不显示图像?

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();
        }

    }

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

最佳答案

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

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

关于java - 图库不会显示已保存的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51935093/

相关文章:

java - 在 AndroidManifest.xml 中添加 "@android:style/Theme.Dialog"后,我的 Android 应用程序崩溃

java - 获取键盘输入并对其运行检查

Android - 如何在 GridView 中放置标签

android - PlayStore - 以下 APK 或应用程序包可在 64 位设备上使用,但只有 native 32 位代码 : 1

android - getContactsFromFirebase() 方法返回一个空列表

javax.inject 不存在

java - 使用 Spring MVC 3 进行正确的表单验证 - 捕获 PersistenceException

java - 如何更改按钮背景的颜色

android - ListView 在调用 notifyDataSetChanged() 时没有得到更新

java - 解析 XML 时出错 : junk after document element - The markup in the document following the root element must be well-formed