How to programmatically resize an image captured by camera in Android

Last updated on April 17, 2013 by Dan Nanni

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);
         ....
     }
}

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean