3

我正在为用户个人资料上传照片。目标是让它在应用程序中作为预览显示,并将其发送到数据库。我能够成功地做到这一点,但是有些照片显示旋转了 90 度。

我查找了一些关于此的信息,似乎使用 ExifInterface 是要走的路?(例如,将图像上传到服务器时图像方向发生变化),但我不确定如何使用 ExifInterface 的位图实现我的 firebase 代码。它是说它的媒体。我尝试过投射并输入许多不同的输入,但似乎无法转换我所拥有的。当我查找转换位图时,另一篇文章说这是不可能的。

应用程序截图(注意左下角旋转的照片):

在此处输入图像描述

我的代码中存在的部分是:

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

整个代码:

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;
        }
    }
}
4

0 回答 0