Search in sources :

Example 1 with PreviewCallback

use of android.hardware.Camera.PreviewCallback in project JustAndroid by chinaltz.

the class CaptureActivity method onCreate.

/**
 * 开始.
 * @param savedInstanceState
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    // 屏幕参数
    int cameraId = this.getIntent().getIntExtra("cameraId", 0);
    int orientation = this.getIntent().getIntExtra("orientation", 0);
    Config.cameraId = cameraId;
    Config.orientation = orientation;
    Config.focusMode = 1;
    // 强制为横屏
    if (Config.orientation == 0) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    setContentView(R.layout.camera_main);
    // 初始化 CameraManager
    CameraManager.init(getApplication());
    surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = (SurfaceHolder) surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    surfaceView.setKeepScreenOn(true);
    // UI相关
    camBtn = (Button) this.findViewById(R.id.shot_btn);
    flashBtn = (Button) this.findViewById(R.id.flash_btn);
    focusBtn = (Button) this.findViewById(R.id.focus_btn);
    okBtn = (Button) this.findViewById(R.id.ok_btn);
    cancleBtn = (Button) this.findViewById(R.id.cancle_btn);
    camLayout = (FrameLayout) this.findViewById(R.id.cam_layout);
    previewLayout = (FrameLayout) this.findViewById(R.id.preview_layout);
    camLayout.setVisibility(View.VISIBLE);
    previewLayout.setVisibility(View.GONE);
    imgResult = (ImageView) this.findViewById(R.id.imgResult);
    if (cameraId == 1) {
        flashBtn.setVisibility(View.GONE);
    }
    okBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.putExtra("path", path);
            setResult(RESULT_OK, intent);
            finish();
        }
    });
    // 拍照的回调
    CameraManager.get().setPictureCallback(new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // 关闭预览
            CameraManager.get().stopPreview();
            Bitmap cameraBitmap = AbImageUtil.getBitmap(data, 1280, 720);
            camLayout.setVisibility(View.INVISIBLE);
            previewLayout.setVisibility(View.VISIBLE);
            imgResult.setImageBitmap(cameraBitmap);
            // 插入到相册数据库
            try {
                String url = insertImage(CaptureActivity.this.getContentResolver(), cameraBitmap, "andbase", "andbase");
                path = getRealFilePath(CaptureActivity.this, Uri.parse(url));
                Log.e("onPictureTaken", "onPictureTaken insertImage:" + path);
                AbToastUtil.showToast(CaptureActivity.this, "insertImage:" + path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    // 对焦的控制
    CameraManager.get().setAutoFocusCallback(new AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            if (success) {
            // 对焦成功
            } else {
            /*//关键代码:自动对焦
					new Handler().postDelayed(new Runnable(){

						@Override
						public void run() {
							CameraManager.get().requestAutoFocus();
						}
						
					}, 1000);*/
            }
            if (Config.focusMode == 1) {
                CameraManager.get().startPreview();
            }
        }
    });
    // 预览
    CameraManager.get().setPreviewCallback(new PreviewCallback() {

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
        }
    });
    // 拍照
    camBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            CameraManager.get().takePicture();
            // 声音
            shootSound();
        }
    });
    // 点击屏幕
    surfaceView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            imgResult.setImageBitmap(null);
            // 继续预览
            CameraManager.get().startPreview();
        }
    });
    // 闪光灯
    flashBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            CameraManager.get().toogleFlash();
        }
    });
    if (Config.focusMode == 0) {
        // 手动对焦
        focusBtn.setVisibility(View.VISIBLE);
        focusBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                CameraManager.get().requestAutoFocus();
            }
        });
    }
    cancleBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            imgResult.setImageBitmap(null);
            camLayout.setVisibility(View.VISIBLE);
            previewLayout.setVisibility(View.INVISIBLE);
            CameraManager.get().startPreview();
        }
    });
}
Also used : PictureCallback(android.hardware.Camera.PictureCallback) Intent(android.content.Intent) SurfaceView(android.view.SurfaceView) ImageView(android.widget.ImageView) View(android.view.View) SurfaceHolder(android.view.SurfaceHolder) Bitmap(android.graphics.Bitmap) PreviewCallback(android.hardware.Camera.PreviewCallback) OnClickListener(android.view.View.OnClickListener) Camera(android.hardware.Camera) AutoFocusCallback(android.hardware.Camera.AutoFocusCallback)

Example 2 with PreviewCallback

use of android.hardware.Camera.PreviewCallback in project haven by guardianproject.

the class Preview method surfaceCreated.

/**
 * Called on the creation of the surface:
 * setting camera parameters to lower possible resolution
 * (preferred is 640x480)
 * in order to minimize CPU usage
 */
public void surfaceCreated(SurfaceHolder holder) {
    if (camera != null)
        stopCamera();
    /*
		 *  The Surface has been created, acquire the camera and tell it where
		 *  to draw.
		 *  If the selected camera is the front one we open it
		 */
    switch(prefs.getCamera()) {
        case PreferenceManager.FRONT:
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            int cameraCount = Camera.getNumberOfCameras();
            for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
                Camera.getCameraInfo(camIdx, cameraInfo);
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    try {
                        camera = Camera.open(camIdx);
                        cameraFacing = Camera.CameraInfo.CAMERA_FACING_FRONT;
                    } catch (RuntimeException e) {
                        Log.e("Preview", "Camera failed to open: " + e.getLocalizedMessage());
                    }
                }
            }
            break;
        case PreferenceManager.BACK:
            camera = Camera.open();
            cameraFacing = Camera.CameraInfo.CAMERA_FACING_BACK;
            break;
        default:
            camera = null;
            break;
    }
    if (camera != null) {
        final Camera.Parameters parameters = camera.getParameters();
        try {
            List<Size> sizesPreviews = parameters.getSupportedPreviewSizes();
            Size bestSize = sizesPreviews.get(0);
            for (int i = 1; i < sizesPreviews.size(); i++) {
                if ((sizesPreviews.get(i).width * sizesPreviews.get(i).height) > (bestSize.width * bestSize.height)) {
                    bestSize = sizesPreviews.get(i);
                }
            }
            parameters.setPreviewSize(bestSize.width, bestSize.height);
        } catch (Exception e) {
            Log.w("Camera", "Error setting camera preview size", e);
        }
        try {
            List<int[]> ranges = parameters.getSupportedPreviewFpsRange();
            int[] bestRange = ranges.get(0);
            for (int i = 1; i < ranges.size(); i++) {
                if (ranges.get(i)[1] > bestRange[1]) {
                    bestRange[0] = ranges.get(i)[0];
                    bestRange[1] = ranges.get(i)[1];
                }
            }
            parameters.setPreviewFpsRange(bestRange[0], bestRange[1]);
        } catch (Exception e) {
            Log.w("Camera", "Error setting frames per second", e);
        }
        try {
            parameters.setAutoExposureLock(false);
            parameters.setExposureCompensation(parameters.getMaxExposureCompensation());
        } catch (Exception e) {
        }
        /*
			 * If the flash is needed
			 */
        if (prefs.getFlashActivation()) {
            Log.i("Preview", "Flash activated");
            parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
        }
        camera.setParameters(parameters);
        try {
            camera.setPreviewDisplay(mHolder);
            camera.setPreviewCallback(new PreviewCallback() {

                public void onPreviewFrame(byte[] data, Camera cam) {
                    Camera.Size size;
                    try {
                        size = cam.getParameters().getPreviewSize();
                    } catch (RuntimeException e) {
                        return;
                    }
                    if (size == null)
                        return;
                    long now = System.currentTimeMillis();
                    if (now < Preview.this.lastTimestamp + PREVIEW_INTERVAL)
                        return;
                    if (!doingProcessing) {
                        Log.i("Preview", "Processing new image");
                        Preview.this.lastTimestamp = now;
                        task = new MotionAsyncTask(lastPic, data, size.width, size.height, updateHandler, motionSensitivity);
                        for (MotionAsyncTask.MotionListener listener : listeners) {
                            Log.i("Preview", "Added listener");
                            task.addListener(listener);
                        }
                        doingProcessing = true;
                        task.addListener(new MotionAsyncTask.MotionListener() {

                            public void onProcess(Bitmap oldBitmap, Bitmap newBitmap, Bitmap rawBitmap, boolean motionDetected) {
                                if (motionDetected) {
                                    Log.i("MotionListener", "Motion detected");
                                    if (serviceMessenger != null) {
                                        Message message = new Message();
                                        message.what = EventTrigger.CAMERA;
                                        try {
                                            File fileImageDir = new File(Environment.getExternalStorageDirectory(), prefs.getImagePath());
                                            fileImageDir.mkdirs();
                                            String ts = new Date().getTime() + ".jpg";
                                            File fileImage = new File(fileImageDir, "detected.original." + ts);
                                            FileOutputStream stream = new FileOutputStream(fileImage);
                                            if (prefs.getCamera().equalsIgnoreCase(PreferenceManager.BACK)) {
                                                Bitmap bmps = ImageCodec.rotate(rawBitmap, 180, false);
                                                bmps.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                                            } else {
                                                rawBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                                            }
                                            stream.flush();
                                            stream.close();
                                            message.getData().putString("path", fileImage.getAbsolutePath());
                                            if (!doingVideoProcessing && prefs.getVideoMonitoringActive()) {
                                                record(camera, serviceMessenger);
                                            }
                                            /**
                                             *												fileImage = new File(fileImageDir, "detected.match." + ts);
                                             *												stream = new FileOutputStream(fileImage);
                                             *												oldBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                                             *												stream.flush();
                                             *												stream.close();
                                             *
                                             *                                                 message.getData().putString("path", fileImage.getAbsolutePath());
                                             */
                                            serviceMessenger.send(message);
                                        } catch (Exception e) {
                                            // Cannot happen
                                            Log.e("Preview", "error creating imnage", e);
                                        }
                                    }
                                }
                                Log.i("MotionListener", "Allowing further processing");
                                doingProcessing = false;
                            }
                        });
                        task.start();
                        lastPic = data;
                        try {
                            Camera.Parameters parameters = cam.getParameters();
                            parameters.setExposureCompensation(parameters.getMaxExposureCompensation());
                            cam.setParameters(parameters);
                        } catch (Exception e) {
                        }
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : Parameters(android.hardware.Camera.Parameters) Parameters(android.hardware.Camera.Parameters) Message(android.os.Message) Size(android.hardware.Camera.Size) IOException(java.io.IOException) MotionAsyncTask(org.havenapp.main.sensors.media.MotionAsyncTask) RemoteException(android.os.RemoteException) IOException(java.io.IOException) Date(java.util.Date) Bitmap(android.graphics.Bitmap) FileOutputStream(java.io.FileOutputStream) PreviewCallback(android.hardware.Camera.PreviewCallback) Camera(android.hardware.Camera) File(java.io.File)

Aggregations

Bitmap (android.graphics.Bitmap)2 Camera (android.hardware.Camera)2 PreviewCallback (android.hardware.Camera.PreviewCallback)2 Intent (android.content.Intent)1 AutoFocusCallback (android.hardware.Camera.AutoFocusCallback)1 Parameters (android.hardware.Camera.Parameters)1 PictureCallback (android.hardware.Camera.PictureCallback)1 Size (android.hardware.Camera.Size)1 Message (android.os.Message)1 RemoteException (android.os.RemoteException)1 SurfaceHolder (android.view.SurfaceHolder)1 SurfaceView (android.view.SurfaceView)1 View (android.view.View)1 OnClickListener (android.view.View.OnClickListener)1 ImageView (android.widget.ImageView)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 Date (java.util.Date)1 MotionAsyncTask (org.havenapp.main.sensors.media.MotionAsyncTask)1