Search code examples
androidpicasso

Why I have this rotation of image?


in my app I need to load image from camera.

This is the code I've used:

private void openCamera()
{
    mMediaUri =getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
    startActivityForResult(photoIntent, REQUEST_TAKE_PHOTO);


}


private Uri getOutputMediaFileUri(int mediaTypeImage)
{
    //check for external storage
    if(isExternalStorageAvaiable())
    {
        File mediaStorageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);

        String fileName = "";
        String fileType = "";
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());

        fileName = "IMG_"+timeStamp;
        fileType = ".jpg";

        File mediaFile;
        try
        {
            mediaFile = File.createTempFile(fileName,fileType,mediaStorageDir);
            Log.i("st","File: "+Uri.fromFile(mediaFile));
        }
        catch (IOException e)
        {
            e.printStackTrace();
            Log.i("St","Error creating file: " + mediaStorageDir.getAbsolutePath() +fileName +fileType);
            return null;
        }
        return FileProvider.getUriForFile(getActivity(),BuildConfig.APPLICATION_ID + ".provider", mediaFile);
    }
    //something went wrong
    return null;

}

private boolean isExternalStorageAvaiable()
{
    String state = Environment.getExternalStorageState();

    if(Environment.MEDIA_MOUNTED.equals(state))
    {
        return true;
    }
    else
    {
        return false;
    }


}

   public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

   if(resultCode == DIALOG_CODE)
    {
        String s = data.getStringExtra("choose");

        if(s.equals(getString(R.string.takephoto)))
        {
          openCamera();
        }
        else if(s.equals(getString(R.string.library)))
        {
          openGallery();
        }
    }
    else if(resultCode == RESULT_OK)
    {
        if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) //dalla fotocamera
        {
            if (data != null)  //caso galleria
            {
                mMediaUri = data.getData();
            }

            Picasso.with(getActivity()).load(mMediaUri).resize(1280, 1280).transform(new RoundedTransformation()).centerCrop().into(photo, new Callback()
            {
                public void onSuccess()
                {

                }

                @Override
                public void onError() {

                }
            });
        }
    }

}

and it works but it gives me this error: if I take a photo like this: enter image description here

it loads a picture in imageview in this way: enter image description here

but if I load the picture from the gallery, it works ok.

What's the error here? Thanks


Solution

  • You have to rotate image using ExifInterface.
    Image rotate based on image capture angle.

    ExifInterface will rotate image even if you click photo from any angle.
    It will display properly.

        File mediaFile = new File(mediaPath);
                Bitmap bitmap;
                if (mediaFile.exists()) {
    
                    if (isImage(mediaPath)) {
    
                        Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath());
                        int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth());
                        Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true);
                        int rotate = 0;
                        try {
                            exif = new ExifInterface(mediaFile.getAbsolutePath());
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                ExifInterface.ORIENTATION_UNDEFINED);
                        switch (orientation) {
                        case ExifInterface.ORIENTATION_NORMAL:
                            rotate = 0;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_270:
                            rotate = 270;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_180:
                            rotate = 180;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_90:
                            rotate = 90;
                            break;
                        }
    
                        Matrix matrix = new Matrix();
                        matrix.postRotate(rotate);
                        Bitmap rotateBitmap = Bitmap.createBitmap(scale, 0, 0, scale.getWidth(),
                                scale.getHeight(), matrix, true);
                        displayImage.setImageBitmap(rotateBitmap);
           }
    }
    public static boolean isImage(String str) {
            boolean temp = false;
            String[] arr = { ".jpeg", ".jpg", ".png", ".bmp", ".gif" };
            for (int i = 0; i < arr.length; i++) {
                temp = str.endsWith(arr[i]);
                if (temp) {
                    break;
                }
            }
            return temp;
        }