-1
public class CustomCameraActivity extends Activity implements
        SurfaceHolder.Callback {
    Camera camera = null;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    boolean previewing = false;
    int flag = 0;
    int which = 0;
    Handler handler;
    private boolean hasFlash;
    private boolean isLighOn;
    private Bitmap surfaceBitmap;
    private Bitmap cameraBitmap;
    private VerticalSeekBar greenSeekbar;
    int vesion = 0;

    public void turn() {
        // myCamera is the Camera object
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
            // only for android older than gingerbread

            if (Camera.getNumberOfCameras() >= 2) {
                vesion = 1;
                camera.stopPreview();
                camera.release();
                // "which" is just an integer flag
                switch (which) {
                case 0:
                    camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
                    which = 1;
                    break;
                case 1:
                    camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
                    which = 0;
                    break;
                }
                try {
                    camera.setPreviewDisplay(surfaceHolder);
                    // "this" is a SurfaceView which implements
                    // SurfaceHolder.Callback,
                    // as found in the code examples
                    camera.setPreviewCallback(null);
                    // camera.setPreviewCallback(this);
                    camera.startPreview();
                } catch (IOException exception) {
                    camera.release();
                    camera = null;
                }
                vesion = 1;
            } else {
                AlertDialog.Builder ab = new AlertDialog.Builder(
                        CustomCameraActivity.this);
                ab.setMessage("Device Having Only one Camera");
                ab.setCancelable(false);
                ab.setPositiveButton("ok",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub

                            }
                        }).show();

            }
        } else {
            AlertDialog.Builder ab1 = new AlertDialog.Builder(
                    CustomCameraActivity.this);
            ab1.setMessage("This Device Does Not Support Dual Camera Feature");
            ab1.setCancelable(false);
            ab1.setPositiveButton("ok", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            }).show();
        }
    }

    private PictureCallback mPicture = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            Constants.data1 = data;
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getWindow().setFormat(PixelFormat.UNKNOWN);
        surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(3);
        this.surfaceView.setBackgroundColor(Color.argb(100, 0,
                MotionEventCompat.ACTION_MASK, 0));

        Button cap_btn = (Button) findViewById(R.id.button01);
        Button retake = (Button) findViewById(R.id.retake);
        Button use = (Button) findViewById(R.id.Use);
        Button back = (Button) findViewById(R.id.back);
        Button home = (Button) findViewById(R.id.home);
        Button turn = (Button) findViewById(R.id.turn);
        turn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                turn();
            }
        });
        home.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                flash();
            }
        });
        back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        use.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (flag >= 1) {
                    startActivity(new Intent(CustomCameraActivity.this,
                            Captured.class));
                } else {
                    AlertDialog.Builder ab1 = new AlertDialog.Builder(
                            CustomCameraActivity.this);
                    ab1.setMessage("Please Capture Image");
                    ab1.setCancelable(false);
                    ab1.setPositiveButton("ok",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub

                                }
                            }).show();
                }
                flag = 0;
            }
        });
        retake.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                camera.startPreview();
                flag = 0;
            }
        });

        cap_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                camera.takePicture(null, null, mPicture);
                flag++;
            }
        });
    }

    public void flash() {
        this.hasFlash = getApplicationContext().getPackageManager()
                .hasSystemFeature("android.hardware.camera.flash");
        if (this.hasFlash) {
            Parameters p = camera.getParameters();
            if (this.isLighOn) {
                p.setFlashMode("off");
                camera.setParameters(p);
                camera.stopPreview();
                camera.startPreview();
                this.isLighOn = false;
                return;
            }
            p.setFlashMode("torch");
            camera.setParameters(p);
            camera.stopPreview();
            camera.startPreview();
            this.isLighOn = true;
            return;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        if (previewing) {
            camera.stopPreview();
            previewing = false;

        }

        if (camera != null) {
            try {
                camera.setPreviewDisplay(surfaceHolder);

                camera.startPreview();
                previewing = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    void setCameraDisplayOrientation(Activity activity, int cameraId,
            Camera camera) {
        if (camera != null) {
            int result;
            CameraInfo info = new CameraInfo();
            int degrees = 0;
            switch (activity.getWindowManager().getDefaultDisplay()
                    .getRotation()) {
            case 0:
                degrees = 0;
                break;
            case 1:
                degrees = 90;
                break;
            case 2:
                degrees = 180;
                break;
            case 3:
                degrees = 270;
                break;
            }
            if (info.facing == 1) {
                result = (360 - ((info.orientation + degrees) % 360)) % 360;
            } else {
                result = ((info.orientation - degrees) + 360) % 360;
            }
            camera.setDisplayOrientation(result);
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            if (vesion == 1) {
                Camera.open(which);
            } else {
                camera = Camera.open();
            }
        } catch (Exception e) {
            camera.release();
        }
        try {
            Parameters parameters = camera.getParameters();
            if (getResources().getConfiguration().orientation != 2) {
                parameters.set("orientation", "portrait");
                camera.setDisplayOrientation(90);
                parameters.setRotation(90);
            } else {
                parameters.set("orientation", "landscape");
                camera.setDisplayOrientation(0);
                parameters.setRotation(0);
            }
            camera.setParameters(parameters);
            camera.setPreviewDisplay(this.surfaceHolder);
        } catch (IOException e2) {
            camera.release();
        }
        camera.startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        camera.stopPreview();
        camera.release();
        camera = null;
        previewing = false;
    }

    public void joinBitmap() {
        this.surfaceView.setBackgroundColor(-16711936);
        this.surfaceView.setDrawingCacheEnabled(true);
        this.surfaceView.buildDrawingCache();
        this.surfaceView.refreshDrawableState();
        new Thread() {
            public void run() {
                try {
                    CustomCameraActivity.this.surfaceBitmap = CustomCameraActivity.this.surfaceView
                            .getDrawingCache();
                    if (CustomCameraActivity.this.surfaceBitmap != null) {
                        File pictureFile = CustomCameraActivity
                                .getOutputMediaFile();
                        if (pictureFile != null) {
                            Bitmap finalbitmap = CustomCameraActivity.overlay(
                                    CustomCameraActivity.this.cameraBitmap,
                                    CustomCameraActivity.this.surfaceBitmap,
                                    CustomCameraActivity.this.greenSeekbar
                                            .getProgress() + 15);
                            if (pictureFile.exists()) {
                                pictureFile.delete();
                            }
                            try {
                                FileOutputStream out = new FileOutputStream(
                                        pictureFile);
                                finalbitmap.compress(CompressFormat.JPEG, 90,
                                        out);
                                out.flush();
                                out.close();
                            } catch (FileNotFoundException e) {
                            } catch (IOException e2) {
                            }
                            CustomCameraActivity.this.handler
                                    .sendEmptyMessage(1);
                            return;
                        }
                        return;
                    }
                    CustomCameraActivity.this.handler.sendEmptyMessage(0);
                } catch (Exception e3) {
                }
            }
        }.start();
    }

    @SuppressLint({ "SimpleDateFormat" })
    private static File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment.getExternalStorageDirectory(),
                "Night Vision Camera");
        if (mediaStorageDir.exists() || mediaStorageDir.mkdirs()) {
            return new File(
                    mediaStorageDir.getPath()
                            + File.separator
                            + "IMG_"
                            + new SimpleDateFormat("yyyyMMdd_HHmmss")
                                    .format(new Date()) + ".jpg");
        }
        return null;
    }

    public static Bitmap overlay(Bitmap bitmap1, Bitmap bitmapOverlay,
            int opacity) {
        Bitmap resultBitmap = Bitmap.createBitmap(bitmapOverlay.getWidth(),
                bitmapOverlay.getHeight(), Config.ARGB_8888);
        Canvas c = new Canvas(resultBitmap);
        c.drawBitmap(bitmap1, 0.0f, 0.0f, null);
        Paint p = new Paint();
        p.setAlpha(opacity);
        c.drawBitmap(bitmapOverlay, 0.0f, 0.0f, p);
        return resultBitmap;
    }
}

Here, I`m creating an image overlay on surface view and when i click on image to capture it, how to save it with that image that is overlayed on it? Please help and thanks in Advance. The image is captured but it is not saved with that image that is overlayed on the surface view.

  • Hmm. Can you remove any code? (Stuff that isn't related to the issue) – evolutionxbox Oct 11 '16 at 07:18
  • Possible duplicate of [Android Take Screenshot of Surface View Shows Black Screen](https://stackoverflow.com/questions/27817577/android-take-screenshot-of-surface-view-shows-black-screen) – Anjani Mittal Nov 22 '18 at 11:29

2 Answers2

1

You can use surfaceview.getDrawingCache();

this will return a Bitmap from your SurfaceView and then you can use it or save it in storage.

Amir Ziarati
  • 14,248
  • 11
  • 47
  • 52
  • actually I`m overlaying an image like what we see in an night vision camera. A green screen on it. so i want to save that image which is captured with the green image – Ashwani Sharma Oct 11 '16 at 07:31
  • Just draw the image on sutfaceView and then get a bitmap out of surface view – Amir Ziarati Oct 11 '16 at 07:57
0

surfaceview.getDrawingCache(); does not work on surface, because surface is separate view than others view you have to get bitmpa on picturetaken method.

 jpegCallback = new PictureCallback() {

        public void onPictureTaken(byte[] data, Camera camera) {

            camera.startPreview();
            Bitmap cameraBitmap = BitmapFactory.decodeByteArray
                    (data, 0, data.length);
            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            pd = new ProgressDialog(MainActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.setTitle("Wait!");
            pd.setMessage("capturing image.........");
            pd.setIndeterminate(false);
            pd.show();

            progressStatus = 0;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (progressStatus < 100) {
                        // Update the progress status
                        progressStatus += 1;

                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                // Update the progress status
                                pd.setProgress(progressStatus);
                                // If task execution completed
                                if (progressStatus == 100) {
                                    // Dismiss/hide the progress dialog
                                    pd.dismiss();
                                }
                            }
                        });
                    }
                }
            }).start();

            Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
            if (rotatedBitmap != null) {
                rotatedBitmap = combinebitmap(rotatedBitmap, bitmapMap);
                Random num = new Random();
                int nu = num.nextInt(1000);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                rotatedBitmap.compress(Bitmap.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 + "LiveCamera");          //<---
                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(),
                            " Image saved at :LiveCamera", Toast.LENGTH_LONG).show();
                    camera.startPreview();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                MediaScannerConnection.scanFile(MainActivity.this,
                        new String[]{dir_image.toString()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, Uri uri) {
                            }
                        });


                safeToTakePicture = true;

            }

        }

    };
Najaf Ali
  • 1,433
  • 16
  • 26