截取屏幕截图并保存到应用程序自己的目录中



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

我有以下代码:

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手机的图库读取。我的代码不执行上述任何操作。当我使用文件资源管理器时,我没有看到任何带有我的应用程序名称的文件夹,并且它也没有出现在库中。似乎它甚至没有保存图像。你能告诉我我的代码有什么问题吗?

下面的代码创建一个名为"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()方法中查找和/或创建一个具有应用名称的目录,然后在目录中返回一个文件名为 timestamp 的文件。然后在takeScreenshot()方法中,将屏幕截图bitmap转换为byte[],并使用fileOutputStream将此byte[]写入getOutputMediaFile()返回的文件。

结果是保存到目录"MyCameraApp"中的图库中的屏幕截图(更改为应用程序的名称(

希望这有帮助!

相关内容

最新更新