Java – The camera parameter setRotation() method does not rotate the frame received in onPreviewFrame().

The camera parameter setRotation() method does not rotate the frame received in onPreviewFrame()…. here is a solution to the problem.

The camera parameter setRotation() method does not rotate the frame received in onPreviewFrame().

I have custom views that extend the SurfaceView and implement Camera.PreviewCallback. I use this View as a camera preview. The ability to capture video frames to buffer and stream them is also implemented.

When the orientation of the device changes, I call setRotation() with the appropriate parameters.

Camera.Parameters parameters = svVideo.getCamera().getParameters();
parameters.setRotation(rotation);
svVideo.getCamera().setParameters(parameters);

Unfortunately, the orientation of the frame captured in the onPreviewFrame() callback has not changed. What I want to achieve is that if I rotate the streaming device, the video stream sent to the other device will rotate accordingly.

I also tried to take some photos that changed the rotation as described. setRotation() only affects the rotation of the photo taken by the front camera (which is strange), and the photo from the rear camera is not affected at all.

My question is: how can I get the correct spin frames available for streaming or rotate them in the callback myself?

Here is my onPreviewFrame method:

@Override
public void onPreviewFrame(final byte[] frame, final Camera camera) {
    final long now = System.nanoTime();
    if (outq.remainingCapacity() >= 2 && (now - this.frame) >= 1000000000 / fps) { //Don't encode more then we can handle, and also not more then FPS.
        queueFrameForEncoding(frame, now);
    }
    getEncodedFrames();
    camera.addCallbackBuffer(frame); Recycle buffer
}

Solution

byte[] rotatedData = new byte[imgToDecode.length]; 
    for (int y = 0; y < imgHeight; y++) {
        for (int x = 0; x < imgWidth; x++)
            rotatedData[x * imgHeight + imgHeight - y - 1] = imgToDecode[x + y * imgWidth];
    }

Similarly, after rotation, you should swap the width and height

int buffer = height;
height = width;
width = buffer;

Related Problems and Solutions