1. Are you ready for the Galaxy S20? Here is everything we know so far!

How to increase image quality in android camera2 api

Discussion in 'Android Development' started by nagamothu, Aug 12, 2019.

  1. nagamothu

    nagamothu Newbie
    Thread Starter

    Hi guys, in my app i have added custom camera using camera2, but the captured image is of 300kb and 240 X 320 resolution. and looks blurry. How can i increase quality of image?
     


  2. wseng92

    wseng92 Android Enthusiast

    Can you post your code?
     
  3. nagamothu

    nagamothu Newbie
    Thread Starter

    Code (Text):
    1.  
    2. public class Custom_CameraActivity extends AppCompatActivity {
    3.  
    4.     private static final String TAG = "MainActivity";
    5.     private static final String CAMERA_BACK = "0" ;
    6.     public static Bitmap rotatedBitmap;
    7.     private ImageButton takePictureButton;
    8.     private TextureView textureView;
    9.     public static Bitmap loadedImage,loadedImage1;
    10.  
    11.     private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    12.     static {
    13.         ORIENTATIONS.append( Surface.ROTATION_0, 90);
    14.         ORIENTATIONS.append(Surface.ROTATION_90, 0);
    15.         ORIENTATIONS.append(Surface.ROTATION_180, 270);
    16.         ORIENTATIONS.append(Surface.ROTATION_270, 180);
    17.     }
    18.     private String cameraId = CAMERA_BACK;
    19.     protected CameraDevice cameraDevice;
    20.     protected CameraCaptureSession cameraCaptureSessions;
    21.     protected CaptureRequest captureRequest;
    22.     protected CaptureRequest.Builder captureRequestBuilder;
    23.     private Size imageDimension;
    24.     private ImageReader imageReader;
    25.     private File file;
    26.     private static final int REQUEST_CAMERA_PERMISSION = 200;
    27.     private boolean mFlashSupported;
    28.     private Handler mBackgroundHandler;
    29.     private HandlerThread mBackgroundThread;
    30.  
    31.     private ImageButton capture,close_camera,flashCameraButton;
    32.  
    33.     private boolean isTorchOn;
    34.     private CameraManager cameraManager;
    35.     private boolean isFlashSupported;
    36.  
    37.  
    38.     @Override
    39.     protected void onCreate(Bundle savedInstanceState) {
    40.         super.onCreate( savedInstanceState );
    41.         setContentView( R.layout.activity_custom__camera );
    42.         textureView = (TextureView) findViewById(R.id.texture);
    43.         assert textureView != null;
    44.         textureView.setSurfaceTextureListener(textureListener);
    45.  
    46.         getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
    47.  
    48.         capture = (ImageButton) findViewById( R.id.captureImage );
    49.         capture.setOnClickListener( new View.OnClickListener() {
    50.             @Override
    51.             public void onClick(View v) {
    52.                 takePicture();
    53.             }
    54.         } );
    55.  
    56.    
    57.         flashCameraButton = (ImageButton) findViewById( R.id.flash );
    58.         isTorchOn=false;
    59.         flashCameraButton.setOnClickListener( new View.OnClickListener() {
    60.             @Override
    61.             public void onClick(View v) {
    62.                 switchFlash();
    63.             }
    64.         } );
    65.  
    66.     }
    67.  
    68.     private void switchFlash() {
    69.         try {
    70.             if (cameraId.equals(CAMERA_BACK)) {
    71.                 if (isFlashSupported) {
    72.                     if (isTorchOn) {
    73.                         captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
    74.                         cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, null);
    75.                         flashCameraButton.setImageResource(R.drawable.bulboff);
    76.                         isTorchOn = false;
    77.                     } else {
    78.                         captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
    79.                         cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, null);
    80.                         flashCameraButton.setImageResource(R.drawable.bulb);
    81.                         isTorchOn = true;
    82.                     }
    83.                 }
    84.             }
    85.         } catch (CameraAccessException e) {
    86.             e.printStackTrace();
    87.         }
    88.     }
    89.  
    90.     TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
    91.         @Override
    92.         public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
    93.             configureTransform(width,height);
    94.             //open your camera here
    95.             openCamera();
    96.         }
    97.         @Override
    98.         public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
    99.             // Transform you image captured size according to the surface width and height
    100.             configureTransform(width,height);
    101.         }
    102.         @Override
    103.         public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
    104.             return false;
    105.         }
    106.         @Override
    107.         public void onSurfaceTextureUpdated(SurfaceTexture surface) {
    108.         }
    109.     };
    110.     private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
    111.         @Override
    112.         public void onOpened(CameraDevice camera) {
    113.             //This is called when the camera is open
    114.             Log.e(TAG, "onOpened");
    115.             cameraDevice = camera;
    116.             createCameraPreview();
    117.             if(null != textureView ){
    118.                 configureTransform(textureView.getWidth(),textureView.getHeight());
    119.             }
    120.         }
    121.  
    122.         @Override
    123.         public void onDisconnected(CameraDevice camera) {
    124.             cameraDevice.close();
    125.         }
    126.  
    127.         @Override
    128.         public void onError(CameraDevice camera, int error) {
    129.             cameraDevice.close();
    130.             cameraDevice = null;
    131.         }
    132.     };
    133.  
    134.  
    135.     private void configureTransform(int viewWidth, int viewHeight) {
    136.         if (null == textureView || null == imageDimension) {
    137.             return;
    138.         }
    139.         int rotation = getWindowManager().getDefaultDisplay().getRotation();
    140.         Matrix matrix = new Matrix();
    141.         RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
    142.         RectF bufferRect = new RectF(0, 0, imageDimension.getHeight(), imageDimension.getWidth());
    143.         float centerX = viewRect.centerX();
    144.         float centerY = viewRect.centerY();
    145.         if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
    146.             bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
    147.             matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
    148.             float scale = Math.max(
    149.                     (float) viewHeight / imageDimension.getHeight(),
    150.                     (float) viewWidth / imageDimension.getWidth());
    151.             matrix.postScale(scale, scale, centerX, centerY);
    152.             matrix.postRotate(90 * (rotation - 2), centerX, centerY);
    153.         }
    154.         textureView.setTransform(matrix);
    155.     }
    156.  
    157.     final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
    158.         @Override
    159.         public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
    160.             super.onCaptureCompleted(session, request, result);
    161.             Toast.makeText(Custom_CameraActivity.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
    162.             createCameraPreview();
    163.         }
    164.     };
    165.     protected void startBackgroundThread() {
    166.         mBackgroundThread = new HandlerThread("Camera Background");
    167.         mBackgroundThread.start();
    168.         mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    169.     }
    170.     protected void stopBackgroundThread() {
    171.         mBackgroundThread.quitSafely();
    172.         try {
    173.             mBackgroundThread.join();
    174.             mBackgroundThread = null;
    175.             mBackgroundHandler = null;
    176.         } catch (InterruptedException e) {
    177.             e.printStackTrace();
    178.         }
    179.     }
    180.     protected void takePicture() {
    181.         if(null == cameraDevice) {
    182.             Log.e(TAG, "cameraDevice is null");
    183.             return;
    184.         }
    185.         CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    186.         try {
    187.             CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
    188.             Size[] jpegSizes = null;
    189.             if (characteristics != null) {
    190.                 jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes( ImageFormat.JPEG);
    191.             }
    192.             int width = 640;
    193.             int height = 480;
    194.             if (jpegSizes != null && 0 < jpegSizes.length) {
    195.                 width = jpegSizes[0].getWidth();
    196.                 height = jpegSizes[0].getHeight();
    197.             }
    198.             ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
    199.             List<Surface> outputSurfaces = new ArrayList <Surface>(2);
    200.             outputSurfaces.add(reader.getSurface());
    201.             outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
    202.             final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
    203.             captureBuilder.addTarget(reader.getSurface());
    204.             //Flash
    205.             if(isTorchOn){
    206.                 captureBuilder.set(captureRequest.CONTROL_AE_MODE,CameraMetadata.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
    207.            captureBuilder.set( CaptureRequest.FLASH_MODE,CameraMetadata.FLASH_MODE_SINGLE );
    208.             }else{
    209.                 captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_ON);
    210.                 captureBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF);
    211.             }
    212.             captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    213.          
    214.             //Quality
    215.             captureBuilder.set(CaptureRequest.JPEG_QUALITY, (byte) 100 );
    216.             // Orientation
    217.             int rotation = getWindowManager().getDefaultDisplay().getRotation();
    218.             captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
    219.             ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
    220.                 @Override
    221.                 public void onImageAvailable(ImageReader reader) {
    222.  
    223.                     Image image = null;
    224.                     try {
    225.                         image = reader.acquireLatestImage();
    226.                         ByteBuffer buffer = image.getPlanes()[0].getBuffer();
    227.                         buffer.rewind();
    228.                         byte[] bytes = new byte[buffer.capacity()];
    229.                         buffer.get(bytes);
    230.                         loadedImage1 = BitmapFactory.decodeByteArray( bytes, 0, bytes.length );
    231.  
    232.                           } catch (Exception e) {
    233.                         e.printStackTrace();
    234.                     } finally {
    235.                         if (image != null) {
    236.                             image.close();
    237.                         }
    238.                     }
    239.                 }
    240.  
    241.             };
    242.             reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
    243.             final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
    244.                 @Override
    245.                 public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
    246.                     super.onCaptureCompleted(session, request, result);
    247.  
    248.                     SimpleDocumentScannerActivity.startScanner(Custom_CameraActivity.this, pathCamera, "");
    249.                 }
    250.             };
    251.             cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
    252.                 @Override
    253.                 public void onConfigured(CameraCaptureSession session) {
    254.                     try {
    255.                         session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
    256.                     } catch (CameraAccessException e) {
    257.                         e.printStackTrace();
    258.                     }
    259.                 }
    260.                 @Override
    261.                 public void onConfigureFailed(CameraCaptureSession session) {
    262.                 }
    263.             }, mBackgroundHandler);
    264.         } catch (CameraAccessException e) {
    265.             e.printStackTrace();
    266.         }
    267.  
    268.  
    269.     }
    270.  
    271.     protected void createCameraPreview() {
    272.         try {
    273.             SurfaceTexture texture = textureView.getSurfaceTexture();
    274.             assert texture != null;
    275.             texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
    276.             Surface surface = new Surface(texture);
    277.             captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
    278.             captureRequestBuilder.addTarget(surface);
    279.             cameraDevice.createCaptureSession( Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
    280.                 @Override
    281.                 public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
    282.                     //The camera is already closed
    283.                     if (null == cameraDevice) {
    284.                         return;
    285.                     }
    286.                     // When the session is ready, we start displaying the preview.
    287.                     cameraCaptureSessions = cameraCaptureSession;
    288.                     updatePreview();
    289.                 }
    290.                 @Override
    291.                 public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
    292.                     Toast.makeText(Custom_CameraActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
    293.                 }
    294.             }, null);
    295.         } catch (CameraAccessException e) {
    296.             e.printStackTrace();
    297.         }
    298.     }
    299.     @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    300.     private void openCamera() {
    301.         CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    302.         Log.e(TAG, "is camera open");
    303.         try {
    304.             cameraId = manager.getCameraIdList()[0];
    305.             CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
    306.             StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
    307.             assert map != null;
    308.             imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
    309.  
    310.             //flash button code
    311.             Boolean available =characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
    312.             isFlashSupported = available == null ? false : available;
    313.             setupFlashButton();
    314.             // Add permission for camera and let user grant the permission
    315.             if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    316.                 ActivityCompat.requestPermissions(Custom_CameraActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
    317.                 return;
    318.             }
    319.             manager.openCamera(cameraId, stateCallback, null);
    320.         } catch (CameraAccessException e) {
    321.             e.printStackTrace();
    322.         }
    323.         Log.e(TAG, "openCamera X");
    324.     }
    325.  
    326.  
    327.  
    328.  
    329.     private void setupFlashButton() {
    330.         if (cameraId.equals(CAMERA_BACK) && isFlashSupported) {
    331.             flashCameraButton.setVisibility(View.VISIBLE);
    332.  
    333.             if (isTorchOn) {
    334.                 flashCameraButton.setImageResource(R.drawable.bulboff);
    335.             } else {
    336.                 flashCameraButton.setImageResource(R.drawable.bulb);
    337.             }
    338.  
    339.         } else {
    340.             flashCameraButton.setVisibility(View.GONE);
    341.         }
    342.     }
    343.  
    344.     @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    345.     protected void updatePreview() {
    346.         if(null == cameraDevice) {
    347.             Log.e(TAG, "updatePreview error, return");
    348.         }
    349.         captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    350.         try {
    351.             cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
    352.         } catch (CameraAccessException e) {
    353.             e.printStackTrace();
    354.         }
    355.     }
    356.  
     
    #3 nagamothu, Aug 12, 2019
    Last edited: Aug 12, 2019
  4. nagamothu

    nagamothu Newbie
    Thread Starter

    Hi can any one tell me How to increase the quality of the images.its Blurry now
     
  5. nagamothu

    nagamothu Newbie
    Thread Starter

  6. nagamothu

    nagamothu Newbie
    Thread Starter

  7. Deleted User

    Deleted User Guest

    Maybe you've just got a crap quality camera on your phone?
     
  8. nagamothu

    nagamothu Newbie
    Thread Starter

    No With Camera i can take good Pictures. Is the code correct? Why it is delayed by 2 -3 seconds after clicking the capture button.
     
  9. nagamothu

    nagamothu Newbie
    Thread Starter

    Yes Done it already.Any other Way
     

    Attached Files:

Loading...

Share This Page

Loading...