簡體   English   中英

上傳到firebase時如何壓縮圖像?

[英]How to compress image while uploading to the firebase?

我正在開發一個社交應用程序,用戶可以在其中將圖像上傳到他們的提要上,但是當用戶拿起圖像時,小於 2 mb 的圖像被拾取並成功上傳到 firebase 但當用戶上傳時圖像超過 2mb 應用程序崩潰。 可以做些什么來壓縮圖像..

活動后.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();
    }

然后,您可以使用以下代碼上傳到 firebase:

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

您可以使用捕獲的圖像創建位圖,如下所示:

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

您還可以查看此第三方庫以壓縮您的圖像單擊此處

//先清除局部變量

位圖位圖; Uri imageUri;

//按鈕動作調用圖片選擇器方法

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

//從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);
    }
}

//先壓縮圖片然后上傳到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
                    }
                }
            });
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM