user8919313
user8919313

Reputation:

(Xamarin.Android) Turn camera picture if the device orientation was landscape

I want to make a Xamarin.Android app where I can capture pictures like the camera...

When I take the picture i have to turn the picture in the correct orientation. So when the orientation was landscape or upside down I want to turn it to portrait... But I don't know how I can do this.

Here is my code

 private async void TakePhotoButtonTapped(object sender, EventArgs e)
    {
        _camera.StopPreview();

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.SetMessage("Search for faces...");
        builder.SetTitle("Warten");

        AlertDialog dialog = builder.Create();

        dialog.Show();

        byte[] imageBytes;

        var image = _textureView.Bitmap;

        using (var imageStream = new MemoryStream())
        {
            await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 50, imageStream);
            image.Recycle();
            imageBytes = imageStream.ToArray();
        }

        var base64image = Convert.ToBase64String(imageBytes);

        FaceRecognition faceRecognition = new FaceRecognition();
        var result = faceRecognition.SendPhoto(base64image);

        dialog.Hide();

        _camera.StartPreview();
    }

Upvotes: 1

Views: 1664

Answers (2)

DerStarkeBaer
DerStarkeBaer

Reputation: 669

To solve the problem you have to update your OnSurfaceTextureUpdated function to this and also alowing screen rotations:

public void OnSurfaceTextureUpdated(SurfaceTexture surface)
    {
    var display = activity.WindowManager.DefaultDisplay;

    if (display.Rotation == SurfaceOrientation.Rotation0)
    {
        _camera.SetDisplayOrientation(90);
    }

    if (display.Rotation == SurfaceOrientation.Rotation90)
    {
        _camera.SetDisplayOrientation(0);
    }

    if (display.Rotation == SurfaceOrientation.Rotation180)
    {
        _camera.SetDisplayOrientation(180);
    }

    if (display.Rotation == SurfaceOrientation.Rotation270)
    {
        _camera.SetDisplayOrientation(180);
    }
}

Upvotes: 0

Diana Li
Diana Li

Reputation: 70

You could use Android.Content.Res.Orientation to get your device orientation, when the orientation was Landscape, use RequestedOrientation to request orientation of the activity.

For example :

if (Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape)
{
    RequestedOrientation = ScreenOrientation.Portrait;
}

Upvotes: 1

Related Questions