首页 > 解决方案 > 截屏并保存到应用程序自己的目录中

问题描述

我知道这个问题已经得到解答,但我想得到一个更好的解释,因为我已经尝试实现它,但它似乎不起作用。

我有以下代码:

private void takeScreenshot() {

        ContextWrapper cw = new ContextWrapper(getApplicationContext());

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

        Date fileName = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", fileName);


        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        File image = new File(directory,fileName+".jpg");
        try {
            FileOutputStream fos = new FileOutputStream(image);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

我想要做的是截取屏幕截图,将其保存到具有我的应用名称的文件夹中,并让它可以被 android 手机的图库读取。我的代码不执行上述任何操作。当我使用文件资源管理器时,我没有看到任何带有我的应用程序名称的文件夹,并且它也没有出现在图库中。似乎它甚至没有保存图像。你能告诉我我的代码有什么问题吗?

标签: javaandroid

解决方案


下面的代码创建了一个名为“AppName”的目录,然后将屏幕截图存储在该目录中。这也将被画廊读取。如果您没有WRITE_EXTERNAL_STORAGE权限,您的代码(以及下面的代码)将无法工作。

        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), "MyCameraApp"); //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("MyCameraApp", "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(TAG, "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(TAG, "File not found" + e.getMessage());
    } catch (Exception e) {

        e.printStackTrace();
    }

}

确保添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

到您的清单并在运行时请求权限

ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    00);

代码在方法中查找和/或创建具有应用程序名称的目录getOutputMediaFile(),然后在目录中返回一个以时间戳为名称的文件。然后在该takeScreenshot()方法中,将屏幕截图bitmap转换为 abyte[]并使用 a将fileOutputStream其写入.byte[]getOutputMediaFile()

结果是保存到“MyCameraApp”目录中画廊的屏幕截图(更改为您的应用程序名称)

希望这可以帮助!


推荐阅读