How to take a screenshot in Android with CameraView (SurfaceView)

1.7k views Asked by At

I'm trying to take screenshot programmatically of an activity with camera running and an overlay on it.

I have already tried the following :

  1. capturing Bitmap and drawing it on a canvas

    The camera part of screen shows up as black

  2. using Open GL

    Couldn't get the overlay part of the screen

I also tried to combine both images, that too did't come out well.

NB : I already went through lot of similar questions, but couldn't find a solution for the same.

I'm using Vuforia cloud reco camera in the activity.

Please help me with this, thanks in advance.

1

There are 1 answers

6
Rishi Paul On

mSnapshotLayout is getting main layout id whose snapshot you want, Like this

mSnapshotLayout = (LinearLayout) findViewById(R.id.snapshotLayout);

Use This inside your button click

View v1 = mSnapshotLayout.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();

storeImage(bm);

And Here is the method to store that Image

@SuppressLint("SimpleDateFormat")
private boolean storeImage(Bitmap imageData) {
    // get path to external storage (SD card)
    String iconsStoragePath = Environment.getExternalStorageDirectory()
            + "/Snapshot/";
    File sdIconStorageDir = new File(iconsStoragePath);

    // create storage directories, if they don't exist
    sdIconStorageDir.mkdirs();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String currentDateandTime = sdf.format(new Date());

    String filename = "Deal" + currentDateandTime + ".png";

    try {

        File file = new File(sdIconStorageDir.toString() + File.separator
                + filename);

        FileOutputStream fileOutputStream = new FileOutputStream(file);

        BufferedOutputStream bos = new BufferedOutputStream(
                fileOutputStream);

        imageData.compress(CompressFormat.PNG, 100, bos);

        bos.flush();
        bos.close();

        MediaScannerConnection.scanFile(this,
                new String[] { file.getPath() },
                new String[] { "image/jpeg" }, null);



    } catch (FileNotFoundException e) {
        Log.w("TAG", "Error saving image file: " + e.getMessage());
        return false;
    } catch (IOException e) {
        Log.w("TAG", "Error saving image file: " + e.getMessage());
        return false;
    }
    return true;
}