List of usage examples for android.media ImageReader newInstance
public static ImageReader newInstance(int width, int height, int format, int maxImages)
Create a new reader for images of the desired size and format.
From source file:Main.java
@TargetApi(Build.VERSION_CODES.KITKAT) public static ImageReader createImageReader(Activity c) { DisplayMetrics metrics = c.getResources().getDisplayMetrics(); int density = metrics.densityDpi; int flags = DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR | DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC; //DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY | DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC; Display display = c.getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size);/*from ww w. j a v a2 s . c om*/ return ImageReader.newInstance(size.x, size.y, PixelFormat.RGB_565, 2); }
From source file:MainActivity.java
protected void takePicture(View view) { if (null == mCameraDevice) { return;//from ww w .j a va 2 s . co m } CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId()); StreamConfigurationMap configurationMap = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (configurationMap == null) return; Size largest = Collections.max(Arrays.asList(configurationMap.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea()); ImageReader reader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, 1); List<Surface> outputSurfaces = new ArrayList<Surface>(2); outputSurfaces.add(reader.getSurface()); outputSurfaces.add(new Surface(mTextureView.getSurfaceTexture())); final CaptureRequest.Builder captureBuilder = mCameraDevice .createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); captureBuilder.addTarget(reader.getSurface()); captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() { @Override public void onImageAvailable(ImageReader reader) { Image image = null; try { image = reader.acquireLatestImage(); ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.capacity()]; buffer.get(bytes); OutputStream output = new FileOutputStream(getPictureFile()); output.write(bytes); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (image != null) { image.close(); } } } }; HandlerThread thread = new HandlerThread("CameraPicture"); thread.start(); final Handler backgroudHandler = new Handler(thread.getLooper()); reader.setOnImageAvailableListener(readerListener, backgroudHandler); final CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) { super.onCaptureCompleted(session, request, result); Toast.makeText(MainActivity.this, "Picture Saved", Toast.LENGTH_SHORT).show(); startPreview(session); } }; mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() { @Override public void onConfigured(CameraCaptureSession session) { try { session.capture(captureBuilder.build(), captureCallback, backgroudHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed(CameraCaptureSession session) { } }, backgroudHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
From source file:com.sien.cpshoot.screencapture.ScreenCaptureFragment.java
private void setUpVirtualDisplay() { Log.i(TAG, "Setting up a VirtualDisplay: " + mSurfaceView.getWidth() + "x" + mSurfaceView.getHeight() + " (" + mScreenDensity + ")"); //---------------cp.add final int w = mSurfaceView.getWidth(); final int h = mSurfaceView.getHeight(); final ImageReader mImageReader = ImageReader.newInstance(w, h, ImageFormat.RGB_565, 2); DisplayMetrics metrics = new DisplayMetrics(); WindowManager mWindowManager = getActivity().getWindowManager(); mWindowManager.getDefaultDisplay().getMetrics(metrics); int mScreenDensity = metrics.densityDpi; //----end/* w w w . j a v a2 s . c o m*/ mVirtualDisplay = mMediaProjection.createVirtualDisplay("ScreenCapture", mSurfaceView.getWidth(), mSurfaceView.getHeight(), mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null); //---------------cp.add new Handler().postDelayed(new Runnable() { @Override public void run() { saveImage(mImageReader, w, h); } }, 100); //-----end mButtonToggle.setText(R.string.stop); }
From source file:com.andrasta.dashi.MainActivity.java
@SuppressWarnings("MissingPermission") private void openCamera(int width, int height) { try {//from ww w.j ava2 s . c o m configBuilder = CameraUtils.initCameraConfig(this, display, width, height); onCameraOrientationSet(configBuilder.getCameraOrientation()); int cameraWidth = configBuilder.getSize().getWidth(); int cameraHeight = configBuilder.getSize().getHeight(); // We fit the aspect ratio of TextureView to the size of preview we picked. int orientation = this.getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { textureView.setAspectRatio(cameraWidth, cameraHeight); laneView.setAspectRatio(cameraWidth, cameraHeight); } else { textureView.setAspectRatio(cameraHeight, cameraWidth); laneView.setAspectRatio(cameraHeight, cameraWidth); } Matrix matrix = CameraUtils.configureTransform(display.getRotation(), width, height, cameraWidth, cameraHeight); textureView.setTransform(matrix); SurfaceTexture texture = textureView.getSurfaceTexture(); if (texture == null) { Log.d(TAG, "No SurfaceTexture"); return; } // We configure the size of default buffer to be the size of camera preview we want. texture.setDefaultBufferSize(cameraWidth, cameraHeight); CameraConfig.Request request = new CameraConfig.Request(CameraDevice.TEMPLATE_PREVIEW, new Surface(texture)); request.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); configBuilder.addRequest(request); Log.d(TAG, "Display camera resolution " + cameraWidth + 'x' + cameraHeight); imageReader = ImageReader.newInstance(cameraRecSize.getWidth(), cameraRecSize.getHeight(), ImageFormat.YUV_420_888, alprHandler.getThreadsNum() + 1); imageReader.setOnImageAvailableListener(this, null); request = new CameraConfig.Request(CameraDevice.TEMPLATE_PREVIEW, imageReader.getSurface()); configBuilder.addRequest(request); Log.d(TAG, "Recognition camera resolution " + cameraRecSize.getWidth() + 'x' + cameraRecSize.getHeight()); camera.open(configBuilder.build()); Log.d(TAG, "Camera opened: " + configBuilder.getCameraId()); } catch (CameraAccessException e) { onError(false, e); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the device onError(true, e); } }
From source file:com.example.camera2apidemo.Camera2Fragment.java
private String setUpCameraOutputs(int width, int height) { Activity activity = getActivity();//from www . j a va 2s . c o m CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { for (String cameraId : manager.getCameraIdList()) { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); // ??? We don't use a front facing camera in this sample. Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { continue; } // ?? ?? StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { continue; } // For still image captures, we use the largest available size. Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea()); mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/2); mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler); // Check if the flash is supported. Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE); mFlashSupported = available == null ? false : available; return cameraId; } } catch (CameraAccessException e) { e.printStackTrace(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. // ErrorDialog.newInstance(getString(R.string.camera_error)) // .show(getChildFragmentManager(), FRAGMENT_DIALOG); } return null; }
From source file:com.flyingcrop.ScreenCaptureFragment.java
public void saveImage() { if (mMediaProjection != null) { final Notification.Builder builder = new Notification.Builder(getActivity()) .setContentTitle(getResources().getString(R.string.fragment_saving_crop)) .setContentText(getResources().getString(R.string.fragment_wait)) .setSmallIcon(com.flyingcrop.R.drawable.ab_ico); final NotificationManager notificationManager = (NotificationManager) getActivity() .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(1, builder.build()); STORE_DIRECTORY = storage;// ww w . j av a 2 s .c o m int flags = DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY | DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC; mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 2); mMediaProjection.createVirtualDisplay("screencap", mWidth, mHeight, mScreenDensity, flags, mImageReader.getSurface(), new VirtualDisplayCallback(), mHandler); if (ServiceIsRunning()) { Intent mIntent = new Intent(getActivity(), Brush.class); getActivity().bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE); } mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() { @Override public void onImageAvailable(ImageReader reader) { image_available = true; Log.d("teste", "image_available : " + image_available.toString()); try { final long time_now = System.currentTimeMillis(); image = mImageReader.acquireLatestImage(); Log.i(TAG, "Time 1 " + (System.currentTimeMillis() - time_now)); if (image != null) { if (ServiceIsRunning()) { if (loop == 0) { View v = mServer.getView(); WindowManager wm = mServer.getWindowM(); if (v != null) wm.removeViewImmediate(v); else mServer.removeAllView(); } loop++; } if (!isFolder()) { Notification.Builder builder = new Notification.Builder(getActivity()) .setContentTitle(getResources().getString(R.string.fragment_error)) .setContentText(getResources().getString(R.string.fragment_error_access)) .setSmallIcon(com.flyingcrop.R.drawable.ab_ico); Toast.makeText(getActivity(), getResources().getString(R.string.fragment_error_toast), Toast.LENGTH_SHORT) .show(); NotificationManager notificationManager = (NotificationManager) getActivity() .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(1, builder.build()); getActivity().finish(); } savePlanes(); } } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } if (bitmap != null) { bitmap.recycle(); } if (image != null) { image.close(); } } } }, null); } }
From source file:com.obviousengine.android.focus.ZslFocusCamera.java
/** * Instantiates a new camera based on Camera 2 API. * * @param device The underlying Camera 2 device. * @param characteristics The device's characteristics. * @param pictureSize the size of the final image to be taken. *///from w w w . ja v a 2s. com ZslFocusCamera(CameraDevice device, CameraCharacteristics characteristics, Size pictureSize) { Timber.v("Creating new ZslFocusCamera"); this.device = device; this.characteristics = characteristics; fullSizeAspectRatio = calculateFullSizeAspectRatio(characteristics); cameraThread = new HandlerThread("FocusCamera"); // If this thread stalls, it will delay viewfinder frames. cameraThread.setPriority(Thread.MAX_PRIORITY); cameraThread.start(); cameraHandler = new Handler(cameraThread.getLooper()); cameraListenerThread = new HandlerThread("FocusCamera-Listener"); cameraListenerThread.start(); cameraListenerHandler = new Handler(cameraListenerThread.getLooper()); // TODO: Encoding on multiple cores results in preview jank due to // excessive GC. int numEncodingCores = Utils.getNumCpuCores(); imageSaverThreadPool = new ThreadPoolExecutor(numEncodingCores, numEncodingCores, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); captureManager = new ImageCaptureManager(MAX_CAPTURE_IMAGES, cameraListenerHandler, imageSaverThreadPool); captureManager.setCaptureReadyListener(new ImageCaptureManager.CaptureReadyListener() { @Override public void onReadyStateChange(boolean capturePossible) { readyStateManager.setInput(ReadyStateRequirement.CAPTURE_MANAGER_READY, capturePossible); } }); // Listen for changes to auto focus state and dispatch to // focusStateListener. captureManager.addMetadataChangeListener(CaptureResult.CONTROL_AF_STATE, new ImageCaptureManager.MetadataChangeListener() { @Override public void onImageMetadataChange(Key<?> key, Object oldValue, Object newValue, CaptureResult result) { if (focusStateListener == null) { return; } focusStateListener.onFocusStatusUpdate( AutoFocusHelper.stateFromCamera2State(result.get(CaptureResult.CONTROL_AF_STATE)), result.getFrameNumber()); } }); // Allocate the image reader to store all images received from the // camera. if (pictureSize == null) { // TODO The default should be selected by the caller, and // pictureSize should never be null. pictureSize = getDefaultPictureSize(); } captureImageReader = ImageReader.newInstance(pictureSize.getWidth(), pictureSize.getHeight(), CAPTURE_IMAGE_FORMAT, MAX_CAPTURE_IMAGES); captureImageReader.setOnImageAvailableListener(captureManager, cameraHandler); mediaActionSound.load(MediaActionSound.SHUTTER_CLICK); }
From source file:com.example.android.tflitecamerademo.Camera2BasicFragment.java
/** * Sets up member variables related to camera. * * @param width The width of available size for camera preview * @param height The height of available size for camera preview *///from w w w. j a v a 2 s . c om private void setUpCameraOutputs(int width, int height) { Activity activity = getActivity(); CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { for (String cameraId : manager.getCameraIdList()) { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); // We don't use a front facing camera in this sample. Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { continue; } StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { continue; } // // For still image captures, we use the largest available size. Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea()); imageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/ 2); // Find out if we need to swap dimension to get the preview size relative to sensor // coordinate. int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation(); // noinspection ConstantConditions /* Orientation of the camera sensor */ int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); boolean swappedDimensions = false; switch (displayRotation) { case Surface.ROTATION_0: case Surface.ROTATION_180: if (sensorOrientation == 90 || sensorOrientation == 270) { swappedDimensions = true; } break; case Surface.ROTATION_90: case Surface.ROTATION_270: if (sensorOrientation == 0 || sensorOrientation == 180) { swappedDimensions = true; } break; default: Log.e(TAG, "Display rotation is invalid: " + displayRotation); } Point displaySize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(displaySize); int rotatedPreviewWidth = width; int rotatedPreviewHeight = height; int maxPreviewWidth = displaySize.x; int maxPreviewHeight = displaySize.y; if (swappedDimensions) { rotatedPreviewWidth = height; rotatedPreviewHeight = width; maxPreviewWidth = displaySize.y; maxPreviewHeight = displaySize.x; } if (maxPreviewWidth > MAX_PREVIEW_WIDTH) { maxPreviewWidth = MAX_PREVIEW_WIDTH; } if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) { maxPreviewHeight = MAX_PREVIEW_HEIGHT; } previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest); // We fit the aspect ratio of TextureView to the size of preview we picked. int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { textureView.setAspectRatio(previewSize.getWidth(), previewSize.getHeight()); } else { textureView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth()); } this.cameraId = cameraId; return; } } catch (CameraAccessException e) { Log.e(TAG, "Failed to access Camera", e); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(), FRAGMENT_DIALOG); } }
From source file:fr.xebia.magritte.classifier.lite.Camera2BasicFragment.java
/** * Sets up member variables related to camera. * * @param width The width of available size for camera preview * @param height The height of available size for camera preview *//*from w w w .j a v a2 s. c o m*/ private void setUpCameraOutputs(int width, int height) { Activity activity = getActivity(); CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { for (String cameraId : manager.getCameraIdList()) { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); // We don't use a front facing camera in this sample. Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { continue; } StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { continue; } // // For still image captures, we use the largest available size. Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea()); imageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/ 2); // Find out if we need to swap dimension to get the preview size relative to sensor // coordinate. int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation(); // noinspection ConstantConditions /* Orientation of the camera sensor */ int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); boolean swappedDimensions = false; switch (displayRotation) { case Surface.ROTATION_0: case Surface.ROTATION_180: if (sensorOrientation == 90 || sensorOrientation == 270) { swappedDimensions = true; } break; case Surface.ROTATION_90: case Surface.ROTATION_270: if (sensorOrientation == 0 || sensorOrientation == 180) { swappedDimensions = true; } break; default: Log.e(TAG, "Display rotation is invalid: " + displayRotation); } Point displaySize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(displaySize); int rotatedPreviewWidth = width; int rotatedPreviewHeight = height; int maxPreviewWidth = displaySize.x; int maxPreviewHeight = displaySize.y; if (swappedDimensions) { rotatedPreviewWidth = height; rotatedPreviewHeight = width; maxPreviewWidth = displaySize.y; maxPreviewHeight = displaySize.x; } if (maxPreviewWidth > MAX_PREVIEW_WIDTH) { maxPreviewWidth = MAX_PREVIEW_WIDTH; } if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) { maxPreviewHeight = MAX_PREVIEW_HEIGHT; } previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest); // We fit the aspect ratio of TextureView to the size of preview we picked. int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { textureView.setAspectRatio(previewSize.getWidth(), previewSize.getHeight()); } else { textureView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth()); } this.cameraId = cameraId; return; } } catch (CameraAccessException e) { e.printStackTrace(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(), FRAGMENT_DIALOG); } }
From source file:com.example.testcamera.Camera2BasicFragmentGoogle.java
/** * Sets up member variables related to camera. * * @param width The width of available size for camera preview * @param height The height of available size for camera preview *//*from ww w .ja va 2s . c o m*/ private void setUpCameraOutputs(int width, int height) { Activity activity = getActivity(); CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { for (String cameraId : manager.getCameraIdList()) { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); // We don't use a front facing camera in this sample. if (characteristics .get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) { continue; } StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); // For still image captures, we use the largest available size. Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea()); mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/2); mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler); // Danger, W.R.! Attempting to use too large a preview size could exceed the camera // bus' bandwidth limitation, resulting in gorgeous previews but the storage of // garbage capture data. mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, largest); // We fit the aspect ratio of TextureView to the size of preview we picked. int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight()); } else { mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth()); } mCameraId = cameraId; return; } } catch (CameraAccessException e) { e.printStackTrace(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. new ErrorDialog().show(getFragmentManager(), "dialog"); } }