0

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);

    }
}
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

0

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

Sanil Khurana
  • 1,129
  • 9
  • 20
0

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

C. Skjerdal
  • 2,750
  • 3
  • 25
  • 50