Android camera resulted image should be rotated after the capture?

GetUsername picture GetUsername · Dec 1, 2011 · Viewed 40.9k times · Source

I'm writing an Android application that uses the camera. I'm setting camera display orientation to 90, my activity is in a portrait orientation:

camera.setDisplayOrientation(90);

I'm getting a well oriented preview picture, but the resulting image is rotated to -90 degrees (counter clockwise) and

exif.getAttribute(ExifInterface.TAG_ORIENTATION)

returns ORIENTATION_NORMAL
Is it expected behavior? Should I rotate resulted image after the capture?

Device - Nexus S, API - 10

Answer

Ameer picture Ameer · Sep 23, 2013

Try this

try {
        File f = new File(imagePath);
        ExifInterface exif = new ExifInterface(f.getPath());
        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);

        int angle = 0;

        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
            angle = 90;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
            angle = 180;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
            angle = 270;
        }

        Matrix mat = new Matrix();
        mat.postRotate(angle);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;

        Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f),
                null, options);
        bitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
                bmp.getHeight(), mat, true);
        ByteArrayOutputStream outstudentstreamOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100,
                outstudentstreamOutputStream);
        imageView.setImageBitmap(bitmap);

    } catch (IOException e) {
        Log.w("TAG", "-- Error in setting image");
    } catch (OutOfMemoryError oom) {
        Log.w("TAG", "-- OOM Error in setting image");
    }

It will work