Android Camera - How can i take a specific "rectangle" from the byte array?

Eyal picture Eyal · Mar 11, 2012 · Viewed 7.9k times · Source

I have created an application that shoots and saves photos. I have a preview and an overlay on top of that preview. The overlay defines a square (the area around the square shows the preview a bit darker), as you can see in the image:

example

What i need to do is to extract the part of the image where the square is. The square is defined like this:

    Rect frame = new Rect(350,50,450,150);

How can i do that? i have the byte array (byte[] data) that i can save, but i want to change the application so that only the square area will be saved.

Edit: i have tried the following:

int[] pixels = new int[100000];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data.length);
            bitmap.getPixels(pixels, 0, 480, 350, 50, 100, 100);
            bitmap = Bitmap.createBitmap(pixels, 0, 100, 100, 100, Config.ARGB_4444);
            bitmap.compress(CompressFormat.JPEG, 0, bos);
            byte[] square = bos.toByteArray();

and then write the array "square" to a new file... The problem is that i get a picture made of lines... there is a problem with the transformation that i made

Answer

Eyal picture Eyal · Mar 12, 2012

It took me some time to figure out that the code should look like this:

int[] pixels = new int[100*100];//the size of the array is the dimensions of the sub-photo
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data.length);
        bitmap.getPixels(pixels, 0, 100, 350, 50, 100, 100);//the stride value is (in my case) the width value
        bitmap = Bitmap.createBitmap(pixels, 0, 100, 100, 100, Config.ARGB_8888);//ARGB_8888 is a good quality configuration
        bitmap.compress(CompressFormat.JPEG, 100, bos);//100 is the best quality possibe
        byte[] square = bos.toByteArray();