Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
like image 282
Martynas Jurkus Avatar asked May 20 '13 14:05

Martynas Jurkus


2 Answers

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);
like image 88
user2453055 Avatar answered Sep 19 '22 13:09

user2453055


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.

like image 22
Alex Cohn Avatar answered Sep 19 '22 13:09

Alex Cohn