我无法在android中以编程方式捕获相机表面视图的屏幕截图。
将图像保存为空白图像。我使用了Root视图。相机表面视图的屏幕截图
下面的代码我试过2种方法。
public void TakeScreenshot(){
Random num = new Random();
int nu=num.nextInt(1000);
View v1 = surfaceView.getRootView();
v1.setDrawingCacheEnabled(true);
v1.buildDrawingCache(true);
Bitmap bmp = Bitmap.createBitmap(v1.getDrawingCache());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
String picId=String.valueOf(nu);
String myfile="Ghost"+picId+".jpeg";
File dir_image = new File(Environment.getExternalStorageDirectory()+
File.separator+"Ultimate Entity Detector");
dir_image.mkdirs();
try {
File tmpFile = new File(dir_image,myfile);
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
Toast.makeText(getApplicationContext(),
"The file is saved at :SD/Ultimate Entity Detector",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
这是第二种方式:
public void shareImage(){
String path=Environment.getExternalStorageDirectory()+File.separator+"Screenshot11.jpeg";
File imageFile=new File(path);
DisplayMetrics dm = MainActivity.this.getResources().getDisplayMetrics();
View v = MainActivity.this.getWindow().getDecorView().findViewById(R.id.lin).getRootView();
v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
OutputStream fout = null ;
try {
fout = new FileOutputStream(imageFile);
returnedBitmap.compress(Bitmap.CompressFormat.JPEG, 90 , fout);
fout.flush();
fout.close();
Toast.makeText(MainActivity.this, "Image saved!", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(MainActivity.this,"File not found!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "IO Exception!", Toast.LENGTH_SHORT).show();
}
}
请包括你到目前为止试过的以及它出错的地方。 – jozxyqk
我已添加代码 – user3563954
或者,http://stackoverflow.com/questions/25086263/take-screenshot-of-surfaceview/。无论如何,各种绘图缓存方法不适用于SurfaceView Surface。如果您只需要相机图像本身,则可以通过Camera API捕获该图像。 – fadden