在上传到Firebase时如何压缩图像?

时间:2018-07-28 11:04:45

标签: java android firebase firebase-storage

我正在开发一个社交应用程序,用户可以在其供稿上上传其图像,但是当用户拾取图像时,小于2 mb的图像将被拾取并成功上传到Firebase,但是当用户上传的图片超过应用崩溃时的2mb。如何压缩图像..

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

3 个答案:

答案 0 :(得分:2)

.values

您可以使用以下代码将其上传到firebase:

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

答案 1 :(得分:0)

您可以使用捕获的图像创建位图,如下所示:

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

您还可以查看此第三方库来压缩图像Click Here

答案 2 :(得分:0)

//先清除局部变量

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