I am creating an app in android in which user will be able to take a picture from front camera in portrait mode only. I have achieved fixing the camera view to portrait but when a picture is taken it appears rotated. The worst thing is that the direction of rotation is different in different phones, in one phone it is right rotated whereas in another it is left rotated.
Here is my code snippets
To make sure activity plays in portrait only
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
To fetch camera
@Override
public void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
Camera.CameraInfo info=new Camera.CameraInfo();
for (int i=0; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
camera=Camera.open(i);
}
}
}
if (camera == null) {
camera=Camera.open();
}
}
To rotate camera
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.setDisplayOrientation(90);
initPreview(width, height);
startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Picture taken
PictureCallback myPictureCallback_JPG = new PictureCallback(){
@Override
public void onPictureTaken(byte[] data, Camera arg1) {
// new SavePhotoTask().execute(data);
Intent myIntent = new Intent(MainActivity.this, CropActivity.class);
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
myIntent.putExtra("image", bitmap);
MainActivity.this.startActivity(myIntent);
}};
The BMP send is always appearing in rotated form, but not always with 90 degree. It looks like android 4.0 not only rotates but flips the image as well. Is there a good way to detect and make sure I always get correct picture?
The issue with mirror and flip was figured out to be specific to android 4.0+, So this worked
Matrix rotateRight = new Matrix();
rotateRight.preRotate(90);
if(android.os.Build.VERSION.SDK_INT>13 && CameraActivity.frontCamera)
{
float[] mirrorY = { -1, 0, 0, 0, 1, 0, 0, 0, 1};
rotateRight = new Matrix();
Matrix matrixMirrorY = new Matrix();
matrixMirrorY.setValues(mirrorY);
rotateRight.postConcat(matrixMirrorY);
rotateRight.preRotate(270);
}
final Bitmap rImg= Bitmap.createBitmap(img, 0, 0,
img.getWidth(), img.getHeight(), rotateRight, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With