I have made an social app for image and video sharing.However,its taking too much time for loading the image.I am using the glide library.Please, tell me how can I reduce the size of image picked up from gallery without considerable change in quality of image (like Instagram do) and then upload it to firebase storage.Please help!
Asked
Active
Viewed 2.1k times
11

Frank van Puffelen
- 565,676
- 79
- 828
- 807

Shubh.J
- 145
- 1
- 2
- 12
-
post your code here – Quick learner Jan 12 '17 at 10:56
-
This sounds like a problem that must have been solved before. Did you try anything? These look promising: http://stackoverflow.com/search?q=%5Bandroid%5D+How+to+reduce+the+size+of+image – Frank van Puffelen Jan 12 '17 at 14:50
-
2Instagram (and many other social media apps) transcode images at lower resolutions and/or in different formats (like webp) so they can serve an appropriate quality image as fast as possible. IG also gets a crazy low quality photo immediately and blurs it with the loading screen, which is a nice effect. You can use tools like imgix or cloudinary to get on-the-fly resized, compressed, photos, or build your own using the GAE Images API (https://cloud.google.com/appengine/docs/python/images/) – Mike McDonald Jan 12 '17 at 15:56
-
How can I do this when uploading from JavaScript? – Feb 25 '17 at 03:10
4 Answers
40
StorageReference childRef2 = [your firebase storage path]
storageRef.child(UserDetails.username+"profilepic.jpg");
Bitmap bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos);
byte[] data = baos.toByteArray();
//uploading the image
UploadTask uploadTask2 = childRef2.putBytes(data);
uploadTask2.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(Profilepic.this, "Upload successful", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Profilepic.this, "Upload Failed -> " + e, Toast.LENGTH_LONG).show();
}
});`
just go ahead and do above steps it will reduce your image size and upload it on firebase it reduce the image size upto 1 to 2 mb like on my experience 4mb file became 304kb .
filepath
is and File
object of your selected image. :)

E.Akio
- 2,249
- 3
- 14
- 27

pratikpchpr
- 419
- 5
- 4
-
1thank you so much,,, Perfectly working for me also.. why no upvote for this answer......+10 – demo Dec 11 '17 at 08:05
-
It worked like a charm, thank you! However, the picture is tilted. How can I fix that? – Ahsan Jun 02 '18 at 16:09
-
thanks, it worked perfectly. Reducing the image of size 5.98 MB to 990 KB – Kartik Agarwal Aug 28 '18 at 09:37
-
1
-
Thank you !!! I have been looking around but others didn't seem to work until I tried yours – Timchang Wuyep Aug 21 '21 at 15:26
4
Here i am using this code to upload compressed image on firebase storeage
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RC_PHOTO_PICKER && resultCode==RESULT_OK)
{
mProgressBar.setVisibility(ProgressBar.VISIBLE);
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(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
String id = chatRoomDataBaseReference.push().getKey();
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
// Set the download URL to the message box, so that the user can send it to the database
FriendlyMessageModel friendlyMessage = new FriendlyMessageModel(id,null, userId, downloadUrl.toString(),time);
chatRoomDataBaseReference.child(id).setValue(friendlyMessage);
}
});
}
}

iamkdblue
- 3,448
- 2
- 25
- 43
0
I have done the same for uploading image to firebase using bitmap.compress
private void postDataToFirebase() {
mProgressDialog.setMessage("Posting the Blog to Firebase");
mProgressDialog.setCancelable(false);
final String titleValue = mPostTitle.getText().toString();
final String description = mPostDescription.getText().toString();
if((!TextUtils.isEmpty(titleValue))&& (!TextUtils.isEmpty(description)) && bitmap != null)
{
mProgressDialog.show();
StorageReference filePath = mStorage.child("Blog_Images").child(imagePathName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(PostActivity.this.getContentResolver(), bitmap, imagePathName, null);
Uri uri = Uri.parse(path);
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabaseReference.push();
newPost.child("Title").setValue(titleValue);
newPost.child("Desc").setValue(description);
newPost.child("imageUrl").setValue(downloadUrl.toString());
Toast.makeText(PostActivity.this, "Data Posted Successfully to Firebase server", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
Intent intent = new Intent(PostActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
bitmap.compress(Bitmap.CompressFormat format, int quality, OutputStream stream)
you can change the quality of the bitmap and compress it.

AndroidBeginner
- 663
- 1
- 9
- 16
0
Kotlin version
val userId = FirebaseAuth.getInstance().currentUser!!.uid
val storageRef = FirebaseStorage.getInstance().getReference("UsersPhotos/${userId}.jpg")
// compressing image
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageURI)
val byteArrayOutputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 25, byteArrayOutputStream)
val reducedImage: ByteArray = byteArrayOutputStream.toByteArray()
storageRef.putBytes(reducedImage)
.addOnSuccessListener {
Log.i("xxx", "Success uploading Image to Firebase!!!")
storageRef.downloadUrl.addOnSuccessListener {
//getting image url
Log.i("xxx",it.toString())
}.addOnFailureListener {
Log.i("xxx", "Error getting image download url")
}
}.addOnFailureListener {
Log.i("xxx", "Failed uploading image to server")
}

Timchang Wuyep
- 629
- 7
- 10