Example usage for android.hardware Camera open

List of usage examples for android.hardware Camera open

Introduction

In this page you can find the example usage for android.hardware Camera open.

Prototype

public static Camera open(int cameraId) 

Source Link

Document

Creates a new Camera object to access a particular hardware camera.

Usage

From source file:com.personal.xiri.only.common.camera.Camera1.java

private void openCamera() {
    if (mCamera != null) {
        releaseCamera();/*from   www  . j a va2 s  .  c o m*/
    }
    mCamera = Camera.open(mCameraId);
    mCameraParameters = mCamera.getParameters();
    // Supported preview sizes
    mPreviewSizes.clear();
    for (Camera.Size size : mCameraParameters.getSupportedPreviewSizes()) {
        mPreviewSizes.add(new Size(size.width, size.height));
    }
    // Supported picture sizes;
    mPictureSizes.clear();
    for (Camera.Size size : mCameraParameters.getSupportedPictureSizes()) {
        mPictureSizes.add(new Size(size.width, size.height));
    }
    // AspectRatio
    if (mAspectRatio == null) {
        mAspectRatio = Constants.DEFAULT_ASPECT_RATIO;
    }
    adjustCameraParameters();
    mCamera.setDisplayOrientation(calcDisplayOrientation(mDisplayOrientation));
    mCallback.onCameraOpened();
}

From source file:io.github.data4all.activity.CameraActivity.java

@Override
protected void onResume() {
    super.onResume();
    this.setLayout();
    if (this.isDeviceSupportCamera()) {
        try {/*  w  ww .j  ava  2  s.c om*/
            cameraPreview = (CameraPreview) findViewById(R.id.cameraPreview);

            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            cameraPreview.setCamera(mCamera);
            mCamera.startPreview();
            this.setListener(btnCapture);
        } catch (RuntimeException ex) {
            Toast.makeText(getApplicationContext(), getString(R.string.noCamSupported), Toast.LENGTH_LONG)
                    .show();
            Log.e(TAG, "device supports no camera", ex);
        }
    } else {
        Toast.makeText(getApplicationContext(), getString(R.string.noCamSupported), Toast.LENGTH_LONG).show();
        finish();
        Log.d(TAG, "device supports no camera");
        return;
    }
    listener.enable();
    Intent intent = new Intent(this, OrientationListener.class);
    bindService(intent, orientationListenerConnection, Context.BIND_AUTO_CREATE);
    this.startService(intent);
}

From source file:com.google.android.cameraview.Camera1.java

private boolean openCamera() {
    if (mCamera != null) {
        releaseCamera();//from  w  ww  .j  ava2 s  . c om
    }

    mCamera = null;
    if (mCameraId == INVALID_CAMERA_ID) {
        mCallback.onCameraNotAvailable();
        return false;
    }

    try {
        mCamera = Camera.open(mCameraId);
    } catch (RuntimeException ex) {
        mCamera = null;
        mCallback.onCameraNotAvailable();
        return false;
    }

    assert (mCamera != null);
    mCameraParameters = mCamera.getParameters();
    // Supported preview sizes
    mPreviewSizes.clear();
    for (Camera.Size size : mCameraParameters.getSupportedPreviewSizes()) {
        mPreviewSizes.add(new Size(size.width, size.height));
    }
    // Supported picture sizes;
    mPictureSizes.clear();
    for (Camera.Size size : mCameraParameters.getSupportedPictureSizes()) {
        mPictureSizes.add(new Size(size.width, size.height));
    }
    // AspectRatio
    if (mAspectRatio == null) {
        mAspectRatio = Constants.DEFAULT_ASPECT_RATIO;
    }
    adjustCameraParameters();
    mCamera.setDisplayOrientation(calcDisplayOrientation(mDisplayOrientation));
    mCallback.onCameraOpened();
    return true;
}

From source file:io.mariachi.allianzvision.camera.api14.Camera1.java

private void openCamera() {
    if (mCamera != null) {
        releaseCamera();/*from   w w w. java 2  s  .  c o m*/
    }
    mCamera = Camera.open(mCameraId);
    mCameraParameters = mCamera.getParameters();
    // Supported preview sizes
    mPreviewSizes.clear();
    for (Camera.Size size : mCameraParameters.getSupportedPreviewSizes()) {
        mPreviewSizes.add(new Size(size.width, size.height));
    }
    // Supported picture sizes;
    mPictureSizes.clear();
    for (Camera.Size size : mCameraParameters.getSupportedPictureSizes()) {
        mPictureSizes.add(new Size(size.width, size.height));
    }
    // AspectRatio
    if (mAspectRatio == null) {
        mAspectRatio = Constants.DEFAULT_ASPECT_RATIO;
    }

    adjustCameraParameters();

    mCamera.setDisplayOrientation(calcCameraRotation(mDisplayOrientation));
    mCallback.onCameraOpened();
}

From source file:com.fatelon.partyphotobooth.fragments.CaptureFragment.java

@Override
public void onResume() {
    super.onResume();

    // Dim system ui for more immersive ui experience.
    dimSystemUi();/*from  w  ww.  j  a  v a2 s .  co m*/

    if (mCameraId != INVALID_CAMERA_ID) {
        try {
            mCamera = Camera.open(mCameraId);

            /*
             * Configure camera parameters.
             */
            Parameters params = mCamera.getParameters();

            // Set auto white balance if supported.
            List<String> whiteBalances = params.getSupportedWhiteBalance();
            if (whiteBalances != null) {
                for (String whiteBalance : whiteBalances) {
                    if (whiteBalance.equals(Camera.Parameters.WHITE_BALANCE_AUTO)) {
                        params.setWhiteBalance(whiteBalance);
                    }
                }
            }

            // Set auto antibanding if supported.
            List<String> antibandings = params.getSupportedAntibanding();
            if (antibandings != null) {
                for (String antibanding : antibandings) {
                    if (antibanding.equals(Camera.Parameters.ANTIBANDING_AUTO)) {
                        params.setAntibanding(antibanding);
                    }
                }
            }

            // Set macro focus mode if supported.
            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes != null) {
                for (String focusMode : focusModes) {
                    if (focusMode.equals(Camera.Parameters.FOCUS_MODE_MACRO)) {
                        params.setFocusMode(focusMode);
                    }
                }
            }

            // Set quality for Jpeg capture.
            params.setJpegQuality(CAPTURED_JPEG_QUALITY);

            // Set optimal size for Jpeg capture.
            Size pictureSize = CameraHelper.getOptimalPictureSize(params.getSupportedPreviewSizes(),
                    params.getSupportedPictureSizes(), ImageHelper.IMAGE_SIZE, ImageHelper.IMAGE_SIZE);
            params.setPictureSize(pictureSize.width, pictureSize.height);

            mCamera.setParameters(params);

            /*
             * Setup preview.
             */
            mPreviewDisplayOrientation = CameraHelper.getCameraScreenOrientation(getActivity(), mCameraId);
            mCamera.setDisplayOrientation(mPreviewDisplayOrientation);
            mPreview.start(mCamera, pictureSize.width, pictureSize.height, mPreviewDisplayOrientation);
        } catch (RuntimeException e) {
            // Call to client.
            ICallbacks callbacks = getCallbacks();
            if (callbacks != null) {
                callbacks.onErrorCameraInUse();
            }
        }
    } else {
        // Call to client.
        ICallbacks callbacks = getCallbacks();
        if (callbacks != null) {
            callbacks.onErrorCameraNone();
        }
    }
}

From source file:org.opencv.samples.facedetect.PlayerViewDemoActivity.java

public void onResume() {
    super.onResume();

    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG).show();
    } else {/*from w ww  .j  av  a  2 s  .c  om*/
        cameraId = findFrontFacingCamera();
        if (cameraId < 0) {
            Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
        } else {
            camera = Camera.open(cameraId);
        }
    }
    camera.startPreview();

    YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
    youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this);

    playListButton = (Button) findViewById(R.id.button1);
    SeekBar seekBar1 = (SeekBar) findViewById(R.id.seekBar1);

    seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // seekBarValue.setText(String.valueOf(progress));
            progress1 = progress;
            ImageView gauge = (ImageView) findViewById(R.id.gaugeImage);

            if (progress <= 6)
                gauge.setImageDrawable(gauges[0]);
            else if (progress > 6 && progress <= 13)
                gauge.setImageDrawable(gauges[1]);
            else if (progress > 13 && progress <= 19)
                gauge.setImageDrawable(gauges[2]);
            else if (progress > 19 && progress <= 25)
                gauge.setImageDrawable(gauges[3]);
            else if (progress > 25 && progress <= 31)
                gauge.setImageDrawable(gauges[4]);
            else if (progress > 31 && progress <= 37)
                gauge.setImageDrawable(gauges[5]);
            else if (progress > 37 && progress <= 43)
                gauge.setImageDrawable(gauges[6]);
            else if (progress > 43 && progress <= 49)
                gauge.setImageDrawable(gauges[7]);
            else if (progress < 49 && progress <= 55)
                gauge.setImageDrawable(gauges[8]);
            else if (progress > 55 && progress <= 61)
                gauge.setImageDrawable(gauges[9]);
            else if (progress > 61 && progress <= 67)
                gauge.setImageDrawable(gauges[10]);
            else if (progress > 67 && progress <= 73)
                gauge.setImageDrawable(gauges[11]);
            else if (progress > 73 && progress <= 79)
                gauge.setImageDrawable(gauges[12]);
            else if (progress > 79 && progress <= 85)
                gauge.setImageDrawable(gauges[13]);
            else if (progress > 85 && progress <= 91)
                gauge.setImageDrawable(gauges[14]);
            else if (progress > 91)
                gauge.setImageDrawable(gauges[15]);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            setIdArray();

        }
    });

    CheckBox checkFd = (CheckBox) findViewById(R.id.checkBox1);
    checkFd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                faceDetection = true;
            else {
                tvTop.setText("Let`s play your mood!");
                faceDetection = false;
            }
        }
    });

    happyImage = (ImageView) findViewById(R.id.hapyFace);
    happyImage.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (faceDetection == false) {
                sadImage.setImageDrawable(getResources().getDrawable(R.drawable.sad_bw));
                happyImage.setImageDrawable(getResources().getDrawable(R.drawable.happy));
                happyImage.bringToFront();
                currentMood = new String("happy");
                setIdArray();
            }
        }
    });

    sadImage = (ImageView) findViewById(R.id.sadFace);
    sadImage.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (faceDetection == false) {
                sadImage.setImageDrawable(getResources().getDrawable(R.drawable.sad));
                happyImage.setImageDrawable(getResources().getDrawable(R.drawable.happy_bw));
                sadImage.bringToFront();
                currentMood = new String("sad");
                setIdArray();
            }
        }
    });

    timerAlert();

    mFacebookBtn = (CheckBox) findViewById(R.id.cb_facebook);

    mProgress = new ProgressDialog(this);
    mFacebook = new Facebook(APP_ID);

    SessionStore.restore(mFacebook, this);

    if (mFacebook.isSessionValid()) {
        mFacebookBtn.setChecked(true);

        String name = SessionStore.getName(this);
        name = (name.equals("")) ? "Unknown" : name;

        mFacebookBtn.setText("  Facebook (" + name + ")");
        mFacebookBtn.setTextColor(Color.WHITE);
    }

    mFacebookBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            onFacebookClick();
        }
    });

}

From source file:org.deviceconnect.android.deviceplugin.host.camera.CameraOverlay.java

private synchronized void showInternal(@NonNull final Callback callback) {
    mHandler.post(new Runnable() {
        @Override/*from   w w  w.j a  va2 s  .  c  o  m*/
        public void run() {
            try {
                mPreview = new Preview(mContext);

                Point size = getDisplaySize();
                int pt = (int) (5 * getScaledDensity());
                WindowManager.LayoutParams l = new WindowManager.LayoutParams(pt, pt,
                        WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                                | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                        PixelFormat.TRANSLUCENT);
                l.x = -size.x / 2;
                l.y = -size.y / 2;
                mWinMgr.addView(mPreview, l);

                mCamera = Camera.open(mCameraId);
                setRequestedPictureSize(mCamera);
                setRequestedPreviewSize(mCamera);
                mPreview.switchCamera(mCameraId, mCamera);
                mCamera.setPreviewCallback(CameraOverlay.this);
                mCamera.setErrorCallback(CameraOverlay.this);

                IntentFilter filter = new IntentFilter();
                filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
                mContext.registerReceiver(mOrientReceiver, filter);

                sendNotification();

                callback.onSuccess();
            } catch (Throwable t) {
                if (BuildConfig.DEBUG) {
                    Log.w("Overlay", "", t);
                }
                callback.onFail();
            }
        }
    });
}

From source file:com.ezartech.ezar.videooverlay.ezAR.java

private void init(JSONArray args, final CallbackContext callbackContext) {
    this.callbackContext = callbackContext;

    supportSnapshot = getSnapshotPlugin() != null;

    if (args != null) {
        String rgb = DEFAULT_RGB;
        try {/*from ww w.  java 2s  . c o  m*/
            rgb = args.getString(0);
        } catch (JSONException e) {
            //do nothing; resort to DEFAULT_RGB
        }

        setBackgroundColor(Color.parseColor(rgb));
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewView.setBackgroundColor(getBackgroundColor());
            }
        });
    }

    if (!PermissionHelper.hasPermission(this, permissions[0])) {
        PermissionHelper.requestPermission(this, CAMERA_SEC, Manifest.permission.CAMERA);
        return;
    }

    JSONObject jsonObject = new JSONObject();
    try {
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics m = new DisplayMetrics();
        display.getMetrics(m);

        jsonObject.put("displayWidth", m.widthPixels);
        jsonObject.put("displayHeight", m.heightPixels);

        int mNumberOfCameras = Camera.getNumberOfCameras();
        Log.d(TAG, "Cameras:" + mNumberOfCameras);

        // Find the ID of the back-facing ("default") camera
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < mNumberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);

            Parameters parameters;
            Camera open = null;
            try {
                open = Camera.open(i);
                parameters = open.getParameters();
            } finally {
                if (open != null) {
                    open.release();
                }
            }

            Log.d(TAG, "Camera facing:" + cameraInfo.facing);

            CameraDirection type = null;
            for (CameraDirection f : CameraDirection.values()) {
                if (f.getDirection() == cameraInfo.facing) {
                    type = f;
                }
            }

            if (type != null) {
                double zoom = 0;
                double maxZoom = 0;
                if (parameters.isZoomSupported()) {
                    maxZoom = (parameters.getMaxZoom() + 1) / 10.0;
                    zoom = Math.min(parameters.getZoom() / 10.0 + 1, maxZoom);
                }

                JSONObject jsonCamera = new JSONObject();
                jsonCamera.put("id", i);
                jsonCamera.put("position", type.toString());
                jsonCamera.put("zoom", zoom);
                jsonCamera.put("maxZoom", maxZoom);
                jsonObject.put(type.toString(), jsonCamera);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Can't set exception", e);
    }

    callbackContext.success(jsonObject);
}

From source file:com.gelakinetic.selfr.CameraActivity.java

/**
 * A safe way to get an instance of the Camera object. Also sets up picture size & focus type
 *
 * @param cameraType Camera.CameraInfo.CAMERA_FACING_FRONT or
 *                   Camera.CameraInfo.CAMERA_FACING_BACK
 * @return A Camera object if it was created, or null
 *//*from   ww w  . ja va2s  .  c o m*/
@Nullable
private static Camera getCameraInstance(int cameraType) {
    Camera camera = null;
    try {
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        /* Scan through all the cameras for one of the specified type */
        for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); camIdx++) {
            Camera.getCameraInfo(camIdx, cameraInfo);
            if (cameraInfo.facing == cameraType) {
                try {
                    /* Open the camera, get default parameters */
                    camera = Camera.open(camIdx);
                    Camera.Parameters parameters = camera.getParameters();

                    /* Set the image to native resolution */
                    List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
                    Camera.Size nativeSize = null;
                    int maxHeight = Integer.MIN_VALUE;
                    for (Camera.Size size : sizes) {
                        if (size.height > maxHeight) {
                            maxHeight = size.height;
                            nativeSize = size;
                        }
                    }
                    if (nativeSize != null) {
                        parameters.setPictureSize(nativeSize.width, nativeSize.height);
                    }

                    /* Set auto-focus, if we can */
                    List<String> focusModes = parameters.getSupportedFocusModes();
                    if (focusModes != null && focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
                    }

                    /* Set the parameters */
                    camera.setParameters(parameters);

                } catch (RuntimeException e) {
                    /* Eat it */
                }
            }
        }
    } catch (Exception e) {
        /* Camera is not available (in use or does not exist) */
    }
    return camera; /* returns null if camera is unavailable */
}

From source file:com.czh.testmpeg.videorecord.CameraActivity.java

public void chooseCamera() {
    if (cameraFront) {
        //???/*from   ww  w .  j a v a2  s . c o m*/
        int cameraId = findBackFacingCamera();
        if (cameraId >= 0) {
            // open the backFacingCamera
            // set a picture callback
            // refresh the preview
            mCamera = Camera.open(cameraId);
            // mPicture = getPictureCallback();
            mPreview.refreshCamera(mCamera);
            reloadQualities(cameraId);
        }
    } else {
        //???
        int cameraId = findFrontFacingCamera();
        if (cameraId >= 0) {
            // open the backFacingCamera
            // set a picture callback
            // refresh the preview
            mCamera = Camera.open(cameraId);
            if (flash) {
                flash = false;
                mBinding.buttonFlash.setImageResource(R.mipmap.ic_flash_off_white);
                mPreview.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            }
            // mPicture = getPictureCallback();
            mPreview.refreshCamera(mCamera);
            reloadQualities(cameraId);
        }
    }
}