1

I need a method to automatically rotate the picture after i have captured it.

It needs to automatically pick up the rotation and correct it.

When i take a photo,It gets rotated 90 degrees anti clockwise.

private void CompressAndSetImage(Uri uri)
    {
        Bitmap thumbnail = null;
        try {
            thumbnail = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), uri);
            int nh = (int) ( thumbnail.getHeight() * (1024.0 / thumbnail.getWidth()) );
            Bitmap scaled = Bitmap.createScaledBitmap(thumbnail, 1024, nh, true);
            Bitmap squareImage = cropToSquare(scaled);
            CurrImageURI =  getImageUri(getActivity().getApplicationContext(), squareImage);
            iv_child.setImageURI(CurrImageURI);
            isImageUploaded = true;

        } catch (IOException e) {
            Toast.makeText(getContext(), "Some error occured", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
private Bitmap cropToSquare(Bitmap bitmap){
        int width  = bitmap.getWidth();
        int height = bitmap.getHeight();
        int newWidth = (height > width) ? width : height;
        int newHeight = (height > width)? height - ( height - width) : height;
        int cropW = (width - height) / 2;
        cropW = (cropW < 0)? 0: cropW;
        int cropH = (height - width) / 2;
        cropH = (cropH < 0)? 0: cropH;
        Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);
        return cropImg;
    }

private Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

Thanks .

RKRK
  • 1,284
  • 5
  • 14
  • 18
Renu
  • 71
  • 1
  • 9
  • You mean,When capture image from camera,come with wrong rotation.So you want to rotate its corret position? – Kabir Aug 14 '19 at 09:36
  • When i capture from camera it shows me the correct view,But when it goes into my image view it rotates – Renu Aug 14 '19 at 09:37

2 Answers2

0

If you're opening camera through intent, the best to solve the rotation problem is to have a temporary fragment with the rotation icon to it. Let user rotate the image itself and post it to your final imageview.

You can also create a custom camera using Android cameraX api, which is a wrapper class to Camera2 Api and with the help of setTargetRotation you can solve the camera rotation problem.

Rishabh Jain
  • 145
  • 8
0

ExifInterface

From official doc:

This is a class for reading and writing Exif tags in a JPEG file or a RAW image file. Supported formats are: JPEG, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW, RAF and HEIF.

Image rotation is often stored in the photo's Exif data, as part of the image file. You can read an image's Exif meta-data using the Android ExifInterface You can use this class for getting the Correct orientation of the image selected from the Default Image gallery.

Apply this code in your app:

First Call the following method with the current Context and the image URI that you want to fix.

public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
            throws IOException {
        int MAX_HEIGHT = 1024;
        int MAX_WIDTH = 1024;

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
        BitmapFactory.decodeStream(imageStream, null, options);
        imageStream.close();

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        imageStream = context.getContentResolver().openInputStream(selectedImage);
        Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);

        img = rotateImageIfRequired(img, selectedImage);
        return img;
    }

CalculateInSampleSize method:

private static int calculateInSampleSize(BitmapFactory.Options options,
                                         int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee a final image
        // with both dimensions larger than or equal to the requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

        final float totalPixels = width * height;

        // Anything more than 2x the requested pixels we'll sample down further
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }
    }
    return inSampleSize;
}

Then comes the method that will check the current image orientation to decide the rotation angle:

private static Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage) throws IOException {

    ExifInterface ei = new ExifInterface(selectedImage.getPath());
    int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            return rotateImage(img, 90);
        case ExifInterface.ORIENTATION_ROTATE_180:
            return rotateImage(img, 180);
        case ExifInterface.ORIENTATION_ROTATE_270:
            return rotateImage(img, 270);
        default:
            return img;
    }
}

Finally the rotation method itself:

private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}

Source of this code:doc

Kabir
  • 852
  • 7
  • 11
  • Thank you, i have added it to my app,Where do i change on my code to implement this – Renu Aug 14 '19 at 09:54
  • When you capture image from camera, you will get Uri of image.Then call handleSamplingAndRotationBitmap().This method return rotate Bitmap. – Kabir Aug 14 '19 at 09:58
  • Ok let me give example.Just post your onActivityResult() result code here. – Kabir Aug 14 '19 at 10:10
  • public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == GALLERY_INT && resultCode == RESULT_OK) { Uri thisUri = data.getData(); CompressAndSetImage(thisUri); } else if (requestCode == CAMERA_INT && resultCode == RESULT_OK) { Uri thisUri = myUri; CompressAndSetImage(thisUri); } } – Renu Aug 14 '19 at 10:15
  • Change code :public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == GALLERY_INT && resultCode == RESULT_OK) { Uri thisUri = data.getData(); CompressAndSetImage(thisUri); } else if (requestCode == CAMERA_INT && resultCode == RESULT_OK) { Uri thisUri = myUri; Bitmap bitmapImage=handleSamplingAndRotationBitmap(getApplicationContext(),thisUri) //CompressAndSetImage(thisUri); } } – Kabir Aug 14 '19 at 10:20
  • im getting error,"cannot resolve method getApplicationContext()" – Renu Aug 14 '19 at 10:25
  • You can also use YourActivityName.this instend getApplicationContext().If you are in fragment ->then use getActivity() – Kabir Aug 14 '19 at 10:26
  • No i replaced with getActivty() and handleSamplingAndRotationBitmap is underlined with red error – Renu Aug 14 '19 at 13:54
  • Put your logcat here or on post question. – Kabir Aug 14 '19 at 14:55
  • I cannot run the app.Within line Bitmap bitmapImage = handleSamplingAndRotationBitmap(getActivity(), thisUri); the handleSamplingAndRotationBitmap is underlined red and when i hover over it i get "unhandled exception" – Renu Aug 14 '19 at 15:56
  • Remove throws IOException from handleSamplingAndRotationBitmap and try to add try...catch inside this method. – Kabir Aug 14 '19 at 16:00
  • You should post logcat of crashing error.Or Check this answer:https://stackoverflow.com/questions/14066038/why-does-an-image-captured-using-camera-intent-gets-rotated-on-some-devices-on-a – Kabir Aug 15 '19 at 09:15