我试图使用一种方法从布局生成位图,并将位图保存到内存中的文件中。但是,getApplicationContext()未解析。
这是方法的代码
private void generateAndSaveBitmap(View layout) {
//Generate bitmap
layout.setDrawingCacheEnabled(true);
layout.buildDrawingCache();
Bitmap imageToSave = layout.getDrawingCache();
//Create a file and path
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File fileName = new File(directory, "sharableImage.jpg");
if (fileName.exists())
fileName.delete();
//Compress and save bitmap under the mentioned fileName
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileName);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// return directory.getAbsolutePath();
}
使用stackoverflow代码的一些帮助来生成此方法。即使在阅读了
getApplicationContext()
上的相关查询后,我也找不到问题所在。任何帮助都将不胜感激编辑:忘了说,方法
generateAndSaveBitmap(View layout)
是在一个单独的类中定义的当做
最佳答案
步骤1:删除ContextWrapper cw = new ContextWrapper(getApplicationContext());
,因为您不需要它。
步骤2:将cw.getDir("imageDir", Context.MODE_PRIVATE);
替换为layout.getContext().getDir("imageDir", Context.MODE_PRIVATE);
另外,请将此磁盘I/O移动到后台线程。