Reputation: 177
I have an app which uploads user image into Firebase storage.
After Intent from the local, the image shows properly in the imageView
, but after uploading to Firebase, it gets rotated to landscape.
This is the code I tried.
private void updatePhoto() {
if(resultUri != null) {
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profile_images").child(userID);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (Exception e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
final UploadTask uploadTask = filePath.putBytes(data);
uploadTask.addOnFailureListener(e -> {
finish();
return;
});
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
uploadTask.addOnSuccessListener(taskSnapshot -> {
filePath.getDownloadUrl().addOnSuccessListener(uri -> {
Map newImage = new HashMap();
newImage.put("profileImage", uri.toString());
userDatabase.updateChildren(newImage);
progressDialog.dismiss();
finish();
});
return;
});
}else{
finish();
}
}
This is my onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri = imageUri;
mProfileImage.setImageURI(resultUri);
}
}
Upvotes: 2
Views: 838
Reputation: 2835
Here's Code to correct Image Position before Upload to Firebase
Check If Image need to rotation
private fun rotateImageIfRequired( context:Context, img:Bitmap, selectedImage:Uri):Bitmap {
// Detect rotation
var rotation = getRotation( context, selectedImage)
if (rotation != 0) {
var matrix:Matrix = Matrix()
matrix.postRotate(rotation as Float)
var rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true)
img.recycle()
return rotatedImg
}
else{
return img
}
}
Rotation Image
fun getRotation( context:Context, imageSelected: Uri):Int{
var rotation = 0
var content: ContentResolver = context.contentResolver
var arr:Array<String> = arrayOf("orientation","date_added")
val mediaCursor:Cursor = content.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arr,
null, null, "date_added desc")
if (mediaCursor != null && mediaCursor.getCount() != 0) {
while(mediaCursor.moveToNext()){
rotation = mediaCursor.getInt(0)
break
}
}
mediaCursor.close()
return rotation
}
Upvotes: 2