简体   繁体   中英

How to compress image while uploading to the firebase?

i am working on the a social app where the user can upload their image on their feeds but when the user is picking up the image ,the image less than 2 mb are getting picked up and are successfully uploaded to the firebase but when the user uploads the image more than 2mb the app crashes. what can be done to compress the image ..

postactivity.java

 private Toolbar mToolbar;
    private ImageButton SelectPostImage;
    private Button UpdatePostButton;
    private ProgressDialog loadingBar;
    private EditText PostDescription;
    private static  final  int Gallery_pick = 1;
    private Uri ImageUri;
    private  String Description;
    private StorageReference PostsImagesReference;
    private DatabaseReference usersRef, PostsRef;
    private  FirebaseAuth mAuth;
    private  String saveCurrentDate, saveCurrentTime,current_user_id, postRandomName, downloadUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
        mAuth = FirebaseAuth.getInstance();
        current_user_id = mAuth.getCurrentUser().getUid();
        PostsImagesReference = FirebaseStorage.getInstance().getReference();
            usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
            PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
        SelectPostImage = (ImageButton)findViewById(R.id.select_post_image);
        UpdatePostButton = (Button) findViewById(R.id.update_post_button);
        PostDescription = (EditText)findViewById(R.id.post_description);
        loadingBar = new ProgressDialog(this);


        mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Update Post");

        SelectPostImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OpenGallery();
            }
        });

        UpdatePostButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ValidatePostInfo();

            }
        });


    }

    private void ValidatePostInfo() {
         Description = PostDescription.getText().toString();
        if (ImageUri == null){
            Toast.makeText(this, "Please select the image", Toast.LENGTH_SHORT).show();

        }
        if (TextUtils.isEmpty(Description)){
            Toast.makeText(this,"Please write something here",Toast.LENGTH_SHORT).show();

        }else {

            loadingBar.setTitle(" Add New Post");
            loadingBar.setMessage("Please wait, while we updating your new post");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);
            StoringImageToFirebaseStorage();

        }
    }

    private void StoringImageToFirebaseStorage() {
        Calendar calForDate = Calendar.getInstance();
        SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
        Calendar calFordTime = Calendar.getInstance();
        SimpleDateFormat currentTime = new SimpleDateFormat("HH: mm");
        saveCurrentTime = currentTime.format(calForDate.getTime());
     postRandomName = saveCurrentDate + saveCurrentTime;

        StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
            filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if (task.isSuccessful()){
                        downloadUrl = task.getResult().getDownloadUrl().toString();
                        Toast.makeText(PostActivity.this,"Image is sucessfully uploaded to storage",Toast.LENGTH_LONG).show();
                        SavingPostInformationToDatabase();

                    }else{
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this,"Error Occured:" + message,Toast.LENGTH_SHORT).show();
                    }
                }
            });

    }

    private void SavingPostInformationToDatabase() {
        usersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){
                    String userfullname = dataSnapshot.child("fullname").getValue().toString();
                    String userProfileImage  = dataSnapshot.child("profileimage").getValue().toString();
                    HashMap postsMap = new HashMap();
                    postsMap.put("uid",current_user_id);
                    postsMap.put("date",saveCurrentDate);

                    postsMap.put("time",saveCurrentTime);

                    postsMap.put("description",Description);

                    postsMap.put("postimage",downloadUrl);
                    postsMap.put("profileimage",userProfileImage);
                    postsMap.put("fullname",userfullname);
                    PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap)
                            .addOnCompleteListener(new OnCompleteListener() {
                                @Override
                                public void onComplete(@NonNull Task task) {
                                    if (task.isSuccessful()){
                                        SendUserToMainActivity();
                                        Toast.makeText(PostActivity.this,"Your New Post is Updated Sucessfully",Toast.LENGTH_SHORT).show();
                                        loadingBar.dismiss();
                                    }else{
                                        Toast.makeText(PostActivity.this,"Error Occured while updating your post .please try again ",Toast.LENGTH_LONG).show();
                                    loadingBar.dismiss();
                                    }
                                }
                            });



                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    private void OpenGallery() {

        Intent galleryIntent = new Intent();
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent, Gallery_pick);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == Gallery_pick && resultCode == RESULT_OK && data != null){
       ImageUri = data.getData();
       SelectPostImage.setImageURI(ImageUri);
    }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home){
            SendUserToMainActivity();
        }

        return super.onOptionsItemSelected(item);
    }

    private void SendUserToMainActivity() {
        Intent mainintent  =  new Intent(PostActivity.this,MainActivity.class);
        startActivity(mainintent);
    }
}
    byte[] thumb_byte_data;
    Uri resultUri = ImageUri;

    //getting imageUri and store in file. and compress to bitmap
    File file_path = new File(resultUri.getPath());
    try {
        Bitmap thumb_bitmap = new Compressor(this)
                .setMaxHeight(200)
                .setMaxWidth(200)
                .setQuality(75)
                .compressToBitmap(file_path);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        thumb_byte_data = baos.toByteArray();

    } catch (IOException e) {
        e.printStackTrace();
    }

You can then upload to firebase with the this code:

 final UploadTask uploadTask = bytepath.putBytes(thumb_byte_data);

                        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                                uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                                    @Override
                                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                                        if (!task.isSuccessful()) {
                                            throw task.getException();
                                        }
                                        // Continue with the task to get the download URL
                                        return filepath.getDownloadUrl();

                                    }
                                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Uri> task) {
                                        if (task.isSuccessful()) {
                                            thumb_download_url = task.getResult().toString();

                                        }
                                    }
                                });

                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                            }
                        });

You can create bitmap with captured image as below:

Bitmap bitmap = Bitmap.createScaledBitmap(yourimageuri, width, height, true);// the uri you got from onactivityresults

You can also view this thirdparty lib to compress your image Click Here

//declear local variable first

Bitmap bitmap; Uri imageUri;

//button action to call Image picker method

companyImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Pick Comapany Image"),GALLERY_REQ_CODE);
        }
    });

//get bitmap from onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GALLERY_REQ_CODE && resultCode == RESULT_OK && data != null) {
        imageUri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        imageView.setImageURI(imageUri);
    }
}

//compress image first then upload to firebase

    public void postImage() {
    StorageReference storageReference = mStorageRef.child("Images/" + //imageName);
    databaseReference = 
    FirebaseDatabase.getInstance().getReference().child("Jobs").child(//imageName);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
    String path = MediaStore.Images.Media.insertImage(SaveJobActivity.this.getContentResolver(),bitmap,//imageName,null);

    Uri uri = Uri.parse(path);
    storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    final String downloadUrl = task.getResult().toString();

                    if (task.isSuccessful()){
                        Map<String, Object> update_hashMap = new HashMap<>();

            //assign download url in hashmap to upadate database reference

                        update_hashMap.put("Image",downloadUrl);

            //update database children here

                        databaseReference.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()){
                                    //do what you want
                                }else {
                                    //show exception
                                }
                            }
                        });
                    }else{
                        //show exception
                    }
                }
            });
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM