I'm using java to develop an android application, I'm using cloud firestore and firebase storage to store the user's profile picture.
When a user logs in, he/she can upload a profile picture and it will be loaded into an imageView,
The images are successfully uploaded to the storage and successfully loaded into the imageView.
However, when I re-run the application and log into the account I uploaded the picture from, the picture can't be loaded into the imageView like before.
Here's my code for uploading the picture:
if (mImageUri != null){
file = mStorageRef.child(userId+".png");
UploadTask = file.putFile(mImageUri).addOnSuccessListener(newOnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(EditDonatorProfile.this,"Image uploaded successfully",Toast.LENGTH_SHORT).show();
String Link = mImageUri.toString();
Upload upload = new Upload(userId,Link);
db.collection("profilePicture").document(userId).set(upload);
}
});
}
else
{
Toast.makeText(this,"Choose a file first",Toast.LENGTH_SHORT).show();
}
and here's my retrieve code:
DocumentReference documentReference1 =db.collection("profilePicture").document(userId);
documentReference1.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
String uri = documentSnapshot.getString("link");
StorageReference storageReference = StorageReference.getReference("Images/"+userId+".png");
if(uri == null)
return;
Uri link = Uri.parse(String.valueOf(uri));
Picasso.with(DonatorProfile.this).load(link).into(Photo);
}
});
getCurrentUser().updateProfile(new UserProfileChangeRequest.Builder()
.setPhotoUri().build());
Related
I want to reduce image file size before I upload it to firebase storage because it take long time to be uploaded.
This is a form which conatins edittext + imageview
I am saving the data(in realtime database) and the image(storage) at the same when clicking on "Save" button.
So how to do to reduce image size or compress it ??
public class PDV_form extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdv_form);
imgproduit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rootNode = FirebaseDatabase.getInstance("https://dtechapp-94795-default-rtdb.europe-west1.firebasedatabase.app");
reference = rootNode.getReference().child("pdv");
String nomcmplt = nomCmplt.getEditText().getText().toString();
String nompdv = nomPdv.getEditText().getText().toString();
String phone = Phone.getEditText().getText().toString();
String adresse = Adresse.getEditText().getText().toString();
String commune = Commune.getEditText().getText().toString();
String wilaya = Wilaya.getEditText().getText().toString();
String codezip = Zip.getEditText().getText().toString();
String email = Email.getEditText().getText().toString();
String imagepdv = placeimgpdv.getDrawable().toString().trim();
UploadDialog = new ProgressDialog(PDV_form.this);
UploadDialog.setTitle("Sauvegarde en cours.... ");
UploadDialog.show();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.FRANCE);
Date now = new Date();
String fileName = formatter.format(now);
storageReference = FirebaseStorage.getInstance().getReference("pdv/" + fileName);
storageReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
placeimgpdv.setImageURI(null);
Toast.makeText(PDV_form.this, "Sauvegarde Terminée", Toast.LENGTH_SHORT).show();
if (UploadDialog.isShowing())
UploadDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (UploadDialog.isShowing())
UploadDialog.dismiss();
Toast.makeText(PDV_form.this, "Sauvegarde Annulée", Toast.LENGTH_SHORT).show();
}
});
StorageReference filpath = storageReference;
filpath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadurl = taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull #NotNull Task<Uri> task) {
String t = task.getResult().toString();
DatabaseReference newPost = reference.child(nomcmplt + "(" + nompdv + ")");
newPost.child("nomcmplt").setValue(nomcmplt);
newPost.child("nompdv").setValue(nompdv);
newPost.child("phone").setValue(phone);
newPost.child("adresse").setValue(adresse);
newPost.child("commune").setValue(commune);
newPost.child("wilaya").setValue(wilaya);
newPost.child("codezip").setValue(codezip);
newPost.child("email").setValue(email);
newPost.child("imagepdv").setValue(task.getResult().toString());
newPost.child("user_id").setValue(uid);
if (task.isSuccessful()) {
startActivity(new Intent(PDV_form.this, Bottom_bar.class));
}
}
});
}
});
}
});
}
private void selectImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, Gallery_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_code && resultCode == RESULT_OK) {
imageUri = data.getData();
placeimgpdv.setImageURI(imageUri);
}
}
}
You are asking two questions, one is to reduce the size of the image and the other is to compress it. I am assuming you meant to compress the image in a lossy sort of way by reducing the size and not zip it. Let me know if that is not what you meant in the comments.
One option you have is to build a solution manually. Python has a bunch of good libraries that can help you do this, for java, I did find a few good resources that work along this direction, this SO question seems to be pretty good - How can I compress images using java?
Another option is to use a SaaS tool. This would really simplify the process for you and for something as simple as this, it probably won't even cost anything unless you are compressing a lot of images, or really really large images. As a starting point, you can check out TinyPNG - https://tinypng.com/. They have a developer API - https://tinypng.com/developers.
Edit: Based on new information regarding volume, updating my answer.
Since you are expecting a low amount of images, you can just use TinyPNG. It is pretty simple to get started. You can just sign up, and you get an API key. They have a nice API that you can use in Java - https://tinypng.com/developers/reference/java
I am trying to solve this as well and it appears nothing else is directly helpful to our situation.
The "Possible Duplicate" examples only works if you convert your image to a bitmap. Which almost all examples of what you are trying to achieve do so with bitmaps. Here is some code from that "duplicate" that should help you. Though after I implemented this, I had trouble dealing with rotation.
Uri selectedImageUri = data.getData();
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//here you can choose quality factor in third parameter(ex. i choosen 25)
bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos);
byte[] fileInBytes = baos.toByteArray();
StorageReference photoref = chatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
//here i am uploading
photoref.putBytes(fileInBytes).addOnSuccessListener....etc
Now while this is probably the correct answer. I myself would prefer a cleaner solution that allows me to compress the file via both an InputStream or a Uri, as that is how I upload images to firebase storage as well.
I might be doing the same and dealing with the bitmap directly, but I intend to search for an alternative solution if I can.
To add there is this extension with firebase which will resize after you upload
my app is simple.
uploading a photo to firebase storage (a profile photo).
then when someone opens the profile. I call the photo from firebase storage.
the problem:
after I uploading a photo to firebase storage, from gallery that I captured using my smartphone, when I am calling it back, the photo got rotated 90 degree in the activity.
but if I uploaded a photo to firebase from my gallery but from another source like (whatsapp) ,
when I call it back. the photo appears in the correct orientation.
any ideas how to solve this problem?
Updated: how i download the photo
final StorageReference ref = FirebaseStorage.getInstance().getReference().child("SomeReference");
try {
final File localFile = File.createTempFile("somephoto", "jpg");
ref.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
System.out.println("onSuccess ");
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
viewHolder.imageViewFriendPhoto.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
System.out.println("onFailure " + e.getMessage());
}
});
} catch (IOException e) {
e.printStackTrace();
}
So, I wanna make the user upload multiple images at the same time to firebase storage. I have done that part successfully but now I want to retrieve the images back. At first, I was uploading one image per user and save the image id to the realtime database so it was very easy to retrieve the image back by the image id. But now how can I save more than one image to the realtime database per user I can't use the same child name because it will be replaced with the old one. Any ideas??
Uploding images and setting the id on realtime database:
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(profuctadd.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(profuctadd.this);
Cursor getimage = databaseHelper.GetPath();
int count = 0;
while (getimage.moveToNext()){
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = arabic.getText().toString()+"-"+System.currentTimeMillis()+"_"+(count++)+"."+getExtension(uri);
System.out.println("IMAGES UPLOADEDDDD: "+ imageid);
String id = getIntent().getStringExtra("storeid");
member.setImageid(imageid);
reference.child(id).child(arname).setValue(member);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(profuctadd.this,showProducts.class);
intent.putExtra("spec",getIntent().getStringExtra("spec"));
intent.putExtra("storeid",getIntent().getStringExtra("storeid"));
startActivity(intent);
DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(profuctadd.this,"Failed",Toast.LENGTH_LONG).show();
}
});
}
}
My firebase db:
you can save more than one image of specific user in images node like that.
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("tL131);
dr.child("images").push().setValue(String.ValueOf(taskSnapshot.getDownloadUrl()));
This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
How can i upload and retrieve an image to firebase storage in android in 2018 (taskSnapshot/getDownloadUrl deprecated) (Closed)
(3 answers)
Closed 2 years ago.
I have this code which uploads an image from imageview on the click of a button. Even if the image gets uploaded by this code, I'm unable to get the download url for the image which I can use in future reference purposes. Kindly help me in getting the download URL. FYI, the getDownloadURl() function has been deprecated and is not working. Thank you!
Button uploadBtn = findViewById(R.id.upload_btn);
uploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseStorage storage = FirebaseStorage.getInstance();
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://'''''''.appspot.com/");
// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageRef.child(System.currentTimeMillis() + ".jpg");
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = storageRef.child("images" + System.currentTimeMillis() + ".jpg");
// While the file names are the same, the references point to different files
mountainsRef.getName().equals(mountainImagesRef.getName()); // true
mountainsRef.getPath().equals(mountainImagesRef.getPath()); // false
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
String downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
Toast.makeText(ClickImage.this, downloadUrl, Toast.LENGTH_SHORT).show();
}
});
}
});
I got this problem with me before, who gets to download Firebase correctly but not the link in downloadUrl.
After what I searched for the matter, there is a thing called AsyncTask and its method of work works to override the orders that need a greater period of time and executes the orders after it and when it is finished it returns to it
Solve this problem You can use this method to retrieve the value of downloadUrl
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnCompleteListener(task -> {
String downloadUrl = Objects.requireNonNull(task.getResult()).toString();
});
I hope I simplified things for you and help you .
I am currently using Firebase to upload an image into Firebase content in Android Studio. Once the file has successfully uploaded, I receive the url of the uploaded image using taskSnapshot.getDownloadUrl(). I want to then put this url in the Firebase Real-time database as a reference. I'm struggling to access the taskSnapshot.getDownloadUrl() from outside the onSuccess() method. Any ideas, please?
I understand that you want to put the uploaded image URL into Firebase Database.
What you can do is, Declare a global variable of type String
private String imageUrl;
Then get the url of image inside onSuccess() method and store in the string
imageUrl = taskSnapshot.getDownloadUrl().toString();
then after the image is uploaded, you have the image URL as string, so just push it to database like this
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("ImageUrl").setValue(imageUrl);
# declare variable like below:
String Storage_Path = "Image_Uploads/";
String Database_Path = "All_Image_Uploads_Database";
# declare firebase storage or real time database variable like below :
StorageReference myrefrence;
DatabaseReference databaseReference;
myrefrence = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
public void UploadImageFileToFirebaseStorage(Uri FilePathUri) {
// Checking whether FilePathUri Is empty or not.
if (FilePathUri != null) {
// Setting progressDialog Title.
// progressDialog.setTitle("Image is Uploading...");
// Showing progressDialog.
// progressDialog.show();
// Creating second StorageReference.
StorageReference storageReference2nd = myrefrence.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));
// Adding addOnSuccessListener to second StorageReference.
storageReference2nd.putFile(FilePathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Getting image name from EditText and store into string variable.
//String TempImageName = ImageName.getText().toString().trim();
// Hiding the progressDialog after done uploading.
// progressDialog.dismiss();
// Showing toast message after done uploading.
//Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
#SuppressWarnings("VisibleForTests")
ImageUploadInfo imageUploadInfo = new ImageUploadInfo("",taskSnapshot.getDownloadUrl().toString());
// Getting image upload ID.
String ImageUploadId = databaseReference.push().getKey();
// Adding image upload id s child element into databaseReference.
databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
}
})
// If something goes wrong .
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Hiding the progressDialog.
//progressDialog.dismiss();
// Showing exception erro message.
// Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
// On progress change upload time.
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// Setting progressDialog Title.
//progressDialog.setTitle("Image is Uploading...");
}
});
} else {
//Toast.makeText(MainActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();
}
}
// Creating Method to get the selected image file Extension from File Path URI.
public String GetFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
// Returning the file Extension.`enter code here`
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}