4

In my application I have added feature of image uploading,It works fine with all the Images except camera image,whenever I browse camera image from gallery and portrait image rotate in 90 degree..following is my snippet code..can anyone help me?I followed so many tutorials but all of them work well in kikat..but when same tutorial does not work with ics,jellybean etc..

public class MainActivity extends Activity {
private Button browse;
private String selectedImagePath="";
private ImageView img;

private TextView messageText;

private static int SELECT_PICTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    img = (ImageView)findViewById(R.id.imagevw);
    browse=(Button)findViewById(R.id.browseimg);
    messageText  = (TextView)findViewById(R.id.messageText);
    browse.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
        }
    });
}
 @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (resultCode == RESULT_OK) {
           if (requestCode == SELECT_PICTURE) {
               Uri selectedImageUri = data.getData();

               /*String filePath = getRealPathFromURI(getActivity(), selectedImageUri );
               messageText.setText(filePath );
               Picasso.with(getActivity())
                                      .load(new File(filePath ))
                                      .centerCrop()
                                      .resize(60, 60).into( img);*/

               selectedImagePath = getPath(selectedImageUri);
               messageText.setText(selectedImagePath);
               System.out.println(requestCode);
               System.out.println("Image Path : " + selectedImagePath);
               img.setImageURI(selectedImageUri);
           }
       }
 }
 @SuppressWarnings("deprecation")
    public String getPath(Uri uri) {
       String[] projection = { MediaStore.Images.Media.DATA };
       Cursor cursor = managedQuery(uri, projection, null, null, null);
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       cursor.moveToFirst();
       return cursor.getString(column_index);
   }

   }
parajs dfsb
  • 145
  • 2
  • 4
  • 13
  • Use `ExifInterface` for that. – Piyush Feb 07 '15 at 06:20
  • Check these http://stackoverflow.com/questions/13511356/android-image-selected-from-gallery-orientation-is-always-0-exif-tag and http://stackoverflow.com/questions/12726860/android-how-to-detect-the-image-orientation-portrait-or-landscape-picked-fro. Your code works only some device. It will not compatible with other large device. So check links. – Piyush Feb 07 '15 at 06:28
  • Answer here http://stackoverflow.com/questions/14066038/why-image-captured-using-camera-intent-gets-rotated-on-some-devices-in-android – Shirish Herwade Aug 23 '16 at 07:44

5 Answers5

15

just include this code

public void rotateImage(String file) throws IOException{

    BitmapFactory.Options bounds = new BitmapFactory.Options();
    bounds.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file, bounds);

    BitmapFactory.Options opts = new BitmapFactory.Options();
    Bitmap bm = BitmapFactory.decodeFile(file, opts);

    int rotationAngle = getCameraPhotoOrientation(getActivity(), Uri.fromFile(file1), file1.toString());

    Matrix matrix = new Matrix();
    matrix.postRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
    Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
    FileOutputStream fos=new FileOutputStream(file);
    rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
}

public static int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath){
    int rotate = 0;
    try {
        context.getContentResolver().notifyChange(imageUri, null);
        File imageFile = new File(imagePath);
        ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);
        switch (orientation) {
        case ExifInterface.ORIENTATION_NORMAL:
            rotate = 0;
        case ExifInterface.ORIENTATION_ROTATE_270:
            rotate = 270;
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            rotate = 180;
            break;
        case ExifInterface.ORIENTATION_ROTATE_90:
            rotate = 90;
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return rotate;
}
Sagar
  • 585
  • 1
  • 9
  • 28
1

There are several methods, but the simplest I found is by using Picasso library. As this is an uploading case, we will get the orientation correct and also can make adjustment in image bitmap size.

Nivedh
  • 971
  • 1
  • 8
  • 19
1
     String filePath = getRealPathFromURI(getActivity(), selectedImageUri );
     messageText.setText(filePath );
     Picasso.with(getActivity())
                            .load(new File(filePath ))
                            .centerCrop()
                            .resize(60, 60).into( img);
Nivedh
  • 971
  • 1
  • 8
  • 19
  • no its not working..still image rotate..and what is profile_image?first read my question carefully – parajs dfsb Feb 07 '15 at 07:27
  • Sorry if its not working. Picasso is handling all this cases and it was working good for me, Thats why I suggest you this method – Nivedh Feb 07 '15 at 08:17
  • Its just a drawable image eg: ic_launcher – Nivedh Feb 07 '15 at 09:20
  • Its just a place holder to show a image before your required image fits the image view.It will work even if its not there. – Nivedh Feb 07 '15 at 09:24
  • ok..thanks for help..but I m new to this..and dont have idea..can you help me?wht should i do – parajs dfsb Feb 07 '15 at 09:33
  • inside your onactivity result use my code. use ic_launcher instead of rofile_image and comment the rest of your code – Nivedh Feb 07 '15 at 09:49
  • i did the same and run my app but its not showing ic_launcher..and I am checking for camera image..same problem like this http://stackoverflow.com/questions/6069122/camera-orientation-issue-in-android – parajs dfsb Feb 07 '15 at 09:56
  • ok then follow that method or else I edited according to yours. – Nivedh Feb 07 '15 at 10:00
0

I solved the image rotation problem with following code

public  Bitmap rotateImageIfRequired(String imagePath) {
    int degrees = 0;

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

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                degrees = 90;
                break;

            case ExifInterface.ORIENTATION_ROTATE_180:
                degrees = 180;
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                degrees = 270;
                break;
        }
    } catch (IOException e) {
        Log.e("ImageError", "Error in reading Exif data of " + imagePath, e);
    }

    BitmapFactory.Options decodeBounds = new BitmapFactory.Options();
    decodeBounds.inJustDecodeBounds = true;

    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, decodeBounds);
    int numPixels = decodeBounds.outWidth * decodeBounds.outHeight;
    int maxPixels = 2048 * 1536; // requires 12 MB heap

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = (numPixels > maxPixels) ? 2 : 1;

    bitmap = BitmapFactory.decodeFile(imagePath, options);

    if (bitmap == null) {
        return null;
    }

    Matrix matrix = new Matrix();
    matrix.setRotate(degrees);

    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
            bitmap.getHeight(), matrix, true);

    return bitmap;
}
Kishor N R
  • 1,521
  • 1
  • 17
  • 23
0

Easy way to do this is by using androidx library.

**implementation 'androidx.exifinterface:exifinterface:1.3.6'**

 //inside on create
   binding.imageViewEditImage.setOnClickListener(view -> {
        Intent gallery = new Intent(Intent.ACTION_PICK, 
   MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        ActivityResultLauncher.launch(gallery);
    });

//for taking picture form gallery 
 ActivityResultLauncher<Intent> ActivityResultLauncher = registerForActivityResult(  //code with exif interface
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent data = result.getData();
                    assert data != null;
                    Uri uri = data.getData();
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                        Bitmap rotatedBitmap = rotateBitmap(bitmap, uri);
                        binding.imageViewUserImage.setImageBitmap(rotatedBitmap);

                        bitmap = Bitmap.createScaledBitmap(rotatedBitmap, 800, 800, false);
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                        binding.imageViewUserImage.setTag(Utility.convert(bitmap));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });



//for devices who take pictures in rotated format this can fix normal image will not rotate
private Bitmap rotateBitmap(Bitmap bitmap, Uri uri) throws IOException {
    InputStream inputStream = getContentResolver().openInputStream(uri);
    ExifInterface exif = null;
    exif = new ExifInterface(inputStream);

    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    Matrix matrix = new Matrix();
    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.postRotate(90);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.postRotate(180);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.postRotate(270);
            break;
        default:
            return bitmap;
    }
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}