Martynas Jurkus
Martynas Jurkus

Reputation: 9301

Rotate byte array of JPEG after onPictureTaken

Is there a way to rotate byte array without decoding it to Bitmap?

Currently in jpeg PictureCallback I just write byte array directly to file. But pictures are rotated. I would like to rotate them without decoding to bitmap with hope that this will conserve my memory.

    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, 0, data.length, o);

    int orientation;
    if (o.outHeight < o.outWidth) {
        orientation = 90;
    } else {
        orientation = 0;
    }

    File photo = new File(tmp, "demo.jpeg");

    FileOutputStream fos;
    BufferedOutputStream bos = null;
    try {
        fos = new FileOutputStream(photo);
        bos = new BufferedOutputStream(fos);
        bos.write(data);
        bos.flush();
    } catch (IOException e) {
        Log.e(TAG, "Failed to save photo", e);
    } finally {
        IOUtils.closeQuietly(bos);
    }

Upvotes: 17

Views: 16589

Answers (4)

Codemaker2015
Codemaker2015

Reputation: 15628

Try like this,

private byte[] rotateImage(byte[] data, int angle) {
    Log.d("labot_log_info","CameraActivity: Inside rotateImage");
    Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, null);
    Matrix mat = new Matrix();
    mat.postRotate(angle);
    bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    return stream.toByteArray();
}

You can call the rotateImage by providing the image data which is getting from onPictureTaken method and an angle for rotation.

Eg: rotateImage(data, 90);

Upvotes: 2

Alex Cohn
Alex Cohn

Reputation: 57203

You can set JPEG rotation via Exif header without decoding it. This is the most efficient method, but some viewers may still show a rotated image.

Alternatively, you can use JPEG lossless rotation. Unfortunately, I am not aware of free Java implementations of this algorithm.

Update on SourceForge, there is a Java open source class LLJTran. The Android port is on GitHub.

Upvotes: 3

user2453055
user2453055

Reputation: 985

Try this. It will solve the purpose.

Bitmap storedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, null);

Matrix mat = new Matrix();                        
mat.postRotate("angle");  // angle is the desired angle you wish to rotate            
storedBitmap = Bitmap.createBitmap(storedBitmap, 0, 0, storedBitmap.getWidth(), storedBitmap.getHeight(), mat, true);

Upvotes: 5

user123
user123

Reputation: 1092

I don't think that there is such possibility. Bytes order depends from picture encoding (png, jpeg). So you are forced to decode image to do something with it.

Upvotes: 2

Related Questions