Flip image stored as a byte[] array

LKB picture LKB · Jun 6, 2013 · Viewed 8.5k times · Source

I have an image which is stored as a byte[] array, and I want to flip the image before I send it off to be processed elsewhere (as a byte[] array).

I've searched around and can't find a simple solution without manipulating each bit in the byte[] array.

What about converting the byte array[] to an image type of some sort, flipping that using an existing flip method, and then converting that back to a byte[] array?

Any advice?

Cheers!

Answer

Voicu picture Voicu · Jun 6, 2013

Byte array to bitmap:

Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

Use this to rotate the image by providing the right angle (180):

public Bitmap rotateImage(int angle, Bitmap bitmapSrc) {
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    return Bitmap.createBitmap(bitmapSrc, 0, 0, 
        bitmapSrc.getWidth(), bitmapSrc.getHeight(), matrix, true);
}

Then back to the array:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] flippedImageByteArray = stream.toByteArray();