How to resize an image captured by camera in Android

Suppose you are working on an Android camera app, and want it to automatically resize camera-captured images to a specific resolution. In this post, I will show you an Android code example that exactly does that.

The first step is of course to capture an image by using camera. For that, you can use Camera.takePicture() API, and pass your own custom Camera.PictureCallback class object as one of its arguments.

Camera.takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)

The Camera.PictureCalback class is responsible for processing (e.g., rotating, resizing, compressing, storing) raw picture data that is captured by Android camera. Hence, image resizing logic can be added inside your Camera.PictureCallback class definition.

The following is an Android sample code of an image resizing function. Given a byte array of raw image, the function resizes the image to a predefined resolution (PHOTO_WIDTH x PHOTO_HEIGHT), and return the resized image as a byte array. What needs to be done inside the function is (1) compress a raw image stored in byte array (by either jpg or png), (2) resize the compressed image, and (3) uncompress it into a new byte array.

byte[] resizeImage(byte[] input) {
    Bitmap original = BitmapFactory.decodeByteArray(input , 0, input.length);
    Bitmap resized = Bitmap.createScaledBitmap(original, PHOTO_WIDTH, PHOTO_HEIGHT, true);
        
    ByteArrayOutputStream blob = new ByteArrayOutputStream();
    resized.compress(Bitmap.CompressFormat.JPEG, 100, blob);

    return blob.toByteArray();
}

In the above example, if you want to use a png encoding format instead of jpg, replace line 6 with the following.

    resized.compress(Bitmap.CompressFormat.PNG, 0, blob); //compression quality is ignored for png

Given resizeImage(), you can define your Camera.PictureCallback class as follows.

private PictureCallback myPictureCallback = new PictureCallback() {
    @Override
     public void onPictureTaken(byte[] data, Camera camera) {
         byte[] resized = resizeImage(data);
         ....
     }
}

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

Leave a comment

Your email address will not be published. Required fields are marked *

Current day month ye@r *