Rotate byte array of JPEG after onPictureTaken

2020-06-01 06:04发布

问题:

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

回答1:

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.



回答2:

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


回答3:

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.