I am not able to capture screenshot of camera surface view pro-grammatically in android.
image getting saved as blank image .I have used Root view.
Below code i have tried 2 ways .
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();
}
}
This is the second way :
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();
}
}