3

I am working on uploading a photo for user profiles. The goal is to have it both show in the app as a preview, and send it to the database. I am able to do that successfully, however some photos are showing rotated 90 degrees.

I looked up some information on this and it seems that working with ExifInterface is the way to go? (e.g. Image orientation changes while uploading Image to server) but I am not sure how to implement the code I have for firebase with the bitmap to ExifInterface. It's saying its taking media. I've tried casting and putting in a number of different inputs but can't seem to convert what I have. When I looked up converting bitmap there was another article saying it is not possible.

Screenshot of the app(notice photo rotated in bottom left):

enter image description here

The part of my code where this exists is:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if(requestCode == RESULT_OK) {
                    Log.i("RegisterActivity", "case 0");
                }
                break;
            case 1:
                if(resultCode == RESULT_OK && data != null) {

                    Uri selectedImage = data.getData();
                    Log.i("RegisterActivity", "selected image = " + selectedImage);
                    //Bitmap imageBitmap = null;
                    try {
                        imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage); //The Image/Photo
                        // https://stackoverflow.com/questions/24629584/image-orientation-changes-while-uploading-image-to-server
                        //File pictureFile = (File) imageBitmap;
                        ExifInterface exif= new ExifInterface();

                        //exif = new ExifInterface();
                        int angle = 0;
                        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                            angle = 90;
                        }
                        else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                            angle = 180;
                        }
                        Matrix matrix1 = new Matrix();
                        //set image rotation value to 45 degrees in matrix.
                        matrix1.postRotate(angle);
                        //Create bitmap with new values.
                        Bitmap photo = Bitmap.createBitmap(imageBitmap, 0, 0, imageBitmap.getWidth(),  imageBitmap.getHeight(), matrix1, true);
                        profilePhoto.setImageBitmap(imageBitmap); //Placing image in ImageView

The entire code:

public class EditProfileActivity extends Activity {

    private EditText firstNameET, lastNameET, passwordET, confirmPasswordET, businessTitleET;
    private String firstName, lastName, password, confirmPassword, businessTitle, uid,currentUserString;
    private ImageView profilePhoto, xImage, checkmarkImage;
    private Button changePhoto;
    private DatabaseReference employeesRef;
    private FirebaseUser currentUser;
    private FirebaseAuth auth;
    private AuthCredential credential;
    FirebaseStorage storage;
    StorageReference storageReference;
    private static final int SELECTED_PICTURE = 1;
    //Test variable
    Uri downloadUrl;
    Bitmap imageBitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);

        //INITIALIZE VARIABLES
        initVariables();


        //UPDATE PHOTO
        changePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("photoBTN","InPhotoBTN");
                handleChooseImage(view);
            }
        });


        //UPDATE DATA FIELDS
        checkmarkImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Log.i("CHECK","INSIDE CHECKMARK");
                updateDBFields();

            } //END ONCLICK
        }); //END ONCLICKLISTENER



    }

    void initVariables(){
        Log.i("initVariables","inside method");
        firstNameET = (EditText) findViewById(R.id.firstNameET);
        lastNameET = (EditText) findViewById(R.id.lastNameET);
        passwordET = (EditText) findViewById(R.id.changePasswordET);
        confirmPasswordET = (EditText) findViewById(R.id.passwordConfirmET);


        profilePhoto = (ImageView) findViewById(R.id.profilePhoto);
        changePhoto = (Button) findViewById(R.id.changePhotoBTN);
        xImage = (ImageView) findViewById(R.id.xImage);
        checkmarkImage = (ImageView) findViewById(R.id.checkmarkImage);
        employeesRef = FirebaseDatabase.getInstance().getReference("Employees");

        currentUser = FirebaseAuth.getInstance().getCurrentUser();
        currentUserString = currentUser.toString();
        Log.i("CurrentUserString", currentUserString);
        storage = FirebaseStorage.getInstance();
        storageReference = storage.getReferenceFromUrl("gs://timeclock-fc.appspot.com/images").child(currentUserString);

        auth = FirebaseAuth.getInstance();
        uid = currentUser.getUid();
    }

    void updateDBFields() {

        firstName = firstNameET.getText().toString().trim();
        lastName = lastNameET.getText().toString().trim();
        password = passwordET.getText().toString().trim();
        confirmPassword = confirmPasswordET.getText().toString().trim();


        //UPDATE NAME
        if(!TextUtils.isEmpty(firstName)) {
            Log.i("UID", uid);
            employeesRef.child(uid).child("firstName").setValue(firstName);
        }

        if(!TextUtils.isEmpty(lastName)) {
            Log.i("UID", uid);
            employeesRef.child(uid).child("lastName").setValue(lastName);
        }

        //UPDATE PASSWORD
        if ( !(TextUtils.isEmpty(password)) && !(TextUtils.isEmpty(confirmPassword)) ) {
            if(password.equals(confirmPassword)) {
                currentUser.updatePassword(password);
                return;
            }
        }
    }

    public void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  //was PNG
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = storageReference.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Log.i("OnFailure", exception.toString());
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(EditProfileActivity.this, "reached onSuccess:", Toast.LENGTH_SHORT).show();
                Log.i("Success", "Reached Success");

                //Get the URL of the Image
                downloadUrl = taskSnapshot.getDownloadUrl();
                //Uri downloadUrl = taskSnapshot.getDownloadUrl();

                //Use a Map for Key/Value pair
                Map<String, Object> map = new HashMap<>();
                map.put("photoDownloadUrl", downloadUrl.toString());

                //Add the URL in the Map to the Firebase DB
                employeesRef.child(currentUser.getUid()).updateChildren(map);
            }
        });
    }

    //Actually opens the CameraRoll
    public void handleChooseImage(View v) {

        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, SELECTED_PICTURE);  //then goes to onActivityResult
    }
    public void handleInsertData(View v) {

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if(requestCode == RESULT_OK) {
                    Log.i("RegisterActivity", "case 0");
                }
                break;
            case 1:
                if(resultCode == RESULT_OK && data != null) {

                    Uri selectedImage = data.getData();
                    Log.i("RegisterActivity", "selected image = " + selectedImage);
                    //Bitmap imageBitmap = null;
                    try {
                        imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage); //The Image/Photo
                        // https://stackoverflow.com/questions/24629584/image-orientation-changes-while-uploading-image-to-server
                        //File pictureFile = (File) imageBitmap;
                        ExifInterface exif= new ExifInterface();

                        //exif = new ExifInterface();
                        int angle = 0;
                        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                            angle = 90;
                        }
                        else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                            angle = 180;
                        }
                        Matrix matrix1 = new Matrix();
                        //set image rotation value to 45 degrees in matrix.
                        matrix1.postRotate(angle);
                        //Create bitmap with new values.
                        Bitmap photo = Bitmap.createBitmap(imageBitmap, 0, 0, imageBitmap.getWidth(),  imageBitmap.getHeight(), matrix1, true);
                        profilePhoto.setImageBitmap(imageBitmap); //Placing image in ImageView
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                    encodeBitmapAndSaveToFirebase(imageBitmap);
                }
                break;
        }
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
ImTheNun
  • 167
  • 1
  • 10
  • profilePhoto.setRotation(profilePhoto.getRotation() + 90); Found this as a way to rotate the ImageView itself... although I will have to find a way to determine IF it needs to be rotated... – ImTheNun Jan 25 '18 at 16:37
  • Glide seems to be working although I can't say I have 100% consistency. The other day it was messing up but today it works for every single picture (I have tried 10 different ones). Glide.with(getApplicationContext()).load(selectedImage).into(profilePhoto); encodeBitmapAndSaveToFirebase(selectedImage); public void encodeBitmapAndSaveToFirebase(Uri uri) { – ImTheNun Jan 31 '18 at 16:22

0 Answers0