如何在上传到firebase时压缩图像



我正在开发一个社交应用程序,用户可以在其订阅源上上传他们的图像,但当用户拾取图像时,小于2mb的图像会被拾取并成功上传到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);
}
}
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

你也可以查看这个第三方库来压缩你的图像点击这里

//declear局部变量first

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

经过几天的艰苦工作和调试。我找到了一个可行的解决方案。

private void decodeFile(Uri filePath) {
// Use bitmap factory to load bitmap from path
Bitmap bmp =null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();

baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos);
byte[] fileInBytes = baos.toByteArray();*/
try {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(filePath, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
bmp = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos);
byte[] fileInBytes = baos.toByteArray();

// For uploading to firebase storage
UploadTask uploadTask = reference.putBytes(fileInBytes);
}

最新更新