您好StackOverflow社区,
在我的应用程序中,我想要一个允许用户捕获当前视图的按钮。
出于这个原因,我编写了以下方法(面向:Android save view to jpg or png):
private LinearLayout container;
public void createImageOfCurrentView(View v) {
if (isExternalStoragePresent()) {
container = (LinearLayout) findViewById(R.id.container);
container.setDrawingCacheEnabled(true);
Bitmap b = container.getDrawingCache();
File dir = new File(Environment.getExternalStorageDirectory().getPath()
+ "/" + getPackageName() + "/");
dir.mkdirs();
File file = new File(dir, "image.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 95, fos); // NullPointerException!
Toast.makeText(this, "The current view has been succesfully saved "
+ "as image.", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "Unfortunatly an error occured and this "
+ "action failed.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Bacause of lacking access to the storage "
+ "of this device, the current view couldn't be saved as an image.",
Toast.LENGTH_LONG).show();
}
}
根据LogCat
问题,在尝试创建NullPointerException
时出现了jpeg
。所以方法container.getDrawingCache()
可能不起作用。在手机上生成文件。但是大小为0字节且没有可见图像。我会感谢任何建议,我必须做的就是让它按照我想要的方式工作。
答案 0 :(得分:0)
我猜我Bitmap b
是null
和perhaps this is the reason?
答案 1 :(得分:0)
试一试 -
public static Bitmap convertViewToBitmap(View view) {
Bitmap result = null;
try {
result = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
view.draw(new Canvas(result));
}catch(Exception e) {}
return result;
}
答案 2 :(得分:0)
试一试 -
view.setDrawingCacheEnabled(true);
Bitmap = bm = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);