Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Android Custom camera

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.16k
    Comment on it

    This tutorial helps you how to create custom camera app, with the help of the following sample code.

    The Custom camera capture the image with auto focus and flash on the click of the capture button.Some developers may require a camera user interface that is customized to the look of their application or provides special features. Creating a customized camera activity requires more code than using an intent, but it can provide a more compelling experience for your users.

    sample code::

    package com.example.androidcamera2;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    
    import android.app.Activity;
    import android.hardware.Camera;
    import android.hardware.Camera.AutoFocusCallback;
    import android.hardware.Camera.Parameters;
    import android.hardware.Camera.PictureCallback;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.FrameLayout;
    
    
    public class MainActivity extends Activity {
    
        private Camera mCamera;
        private CameraPreview mPreview;
        public static final int MEDIA_TYPE_IMAGE =1;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Create an instance of Camera
            mCamera = getCameraInstance();
    
            // Create our Preview view and set it as the content of our activity.
            mPreview = new CameraPreview(this, mCamera);
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mPreview);
    
            final PictureCallback mPicture = new PictureCallback() {
    
                public void onPictureTaken(byte[] data, Camera camera) {
    
                    File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
    
                    if (pictureFile == null) {
                        return;
                    }
    
                    try {
                        FileOutputStream fos = new FileOutputStream(pictureFile);
                        fos.write(data);
                        fos.close();
                        MediaStore.Images.Media.insertImage(getContentResolver(),
                                pictureFile.getAbsolutePath(),
                                pictureFile.getName(), pictureFile.getName());
                    } catch (FileNotFoundException e) {
    
                    } catch (IOException e) {
    
                    }
                }
            };
    
            Parameters params = mCamera.getParameters();
    
            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Parameters.FOCUS&#95;MODE&#95;AUTO)) {
              // Autofocus mode is supported
                params.setFocusMode(Parameters.FOCUS&#95;MODE&#95;AUTO);
                params.setFlashMode(Parameters.FLASH&#95;MODE&#95;ON);
                mCamera.setParameters(params);
            }
    
            Button captureButton = (Button) findViewById(R.id.button&#95;capture);
            captureButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // get an image from the camera
                    mCamera.autoFocus(new AutoFocusCallback() {
                        @Override
                        public void onAutoFocus(boolean arg0, Camera arg1) {
                            mCamera.takePicture(null,null,mPicture);
                            //mCamera.stopPreview();
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            mCamera.startPreview();                     
                        }
                    });
                }
            });
    
        }
    
        public static Camera getCameraInstance() {
            Camera c = null;
            try {
                c = Camera.open(); // attempt to get a Camera instance
            } catch (Exception e) {
                // Camera is not available (in use or does not exist)
            }
            return c; // returns null if camera is unavailable
        }
    
    
        @Override
        protected void onPause() {
            super.onPause();
            releaseCamera();              // release the camera immediately on pause event
        }
    
    
    
        private void releaseCamera(){
            if (mCamera != null){
                mCamera.release();        // release the camera for other applications
                mCamera = null;
            }
        }
        private static File getOutputMediaFile(int m) {
            File mediaStorageDir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY&#95;PICTURES),
                    "MyCameraApp");
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("MyCameraApp", "failed to create directory");
                    return null;
                }
            }
            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd&#95;HHmmss")
                    .format(new Date());
            File mediaFile;
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG&#95;" + timeStamp + ".jpg");
    
            return mediaFile;
        }
    
    }
    

    Preview activity

    package com.example.androidcamera2;
    
    import java.io.IOException;
    import java.util.List;
    
    import android.content.Context;
    import android.hardware.Camera;
    import android.hardware.Camera.Size;
    import android.util.Log;
    import android.view.Surface;
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.WindowManager;
    
    
    public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
        private SurfaceHolder mHolder;
        private Camera mCamera;
    
        public CameraPreview(Context context, Camera camera) {
            super(context);
            mCamera = camera;
    
            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = getHolder();
            mHolder.addCallback(this);
            //deprecated setting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
    
        public void surfaceCreated(SurfaceHolder holder) {
            // The Surface has been created, now tell the camera where to draw the preview.
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
                //Log.d(TAG, "Error setting camera preview: " + e.getMessage());
            }
        }
    
        public void surfaceDestroyed(SurfaceHolder holder) {
            // empty. Take care of releasing the Camera preview in your activity.
        }
    
        public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
            // If your preview can change or rotate, take care of those events here.
            // Make sure to stop the preview before resizing or reformatting it.
    
            if (mHolder.getSurface() == null){
              // preview surface does not exist
              return;
            }
    
            // stop preview before making changes
            try {
                mCamera.stopPreview();
            } catch (Exception e){
              // ignore: tried to stop a non-existent preview
            }
    
            // set preview size and make any resize, rotate or
            // reformatting changes here
    
            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();
    
            } catch (Exception e){
                //Log.d(TAG, "Error starting camera preview: " + e.getMessage());
            }
        }
    }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: