Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress an image file in Android?

So for each image I have its path (in the form of a string). And I convert that path string to a file. I then store that file into Firebase storage, but my problem is that the file is too large when I query. So I need to compress it before uploading it Firebase storage. I was looking around, but never found a clear cut solution on how to do this. Please if anyone can help me with very clear and simple solution that would be great. Below is my code.

for(String path : images)
{
    try {
    InputStream stream = new FileInputStream(new File(path));
    UploadTask uploadTask = imageStorage.putStream(stream);
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
            Log.d("myStorage","failure :(");
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
            UrI downloadUrl = taskSnapshot.getDownloadUrl();
            Log.d("myStorage","success!");
        }
    });
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }
    countDB++;

}
like image 720
TheQ Avatar asked Feb 03 '26 09:02

TheQ


1 Answers

I have a custom class for Image Compression which I used for Firebase Storage, and the size was reduced significantly.

This class can be used to compress a Bitmap and also a File before sending to Firebase

public class ImageCompression {

public static Bitmap getThumbnail(Uri uri, Context context) throws FileNotFoundException, IOException {
    InputStream input = context.getContentResolver().openInputStream(uri);

    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither = true;//optional
    onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();
    if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
        return null;

    int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;

    double ratio = (originalSize > 500) ? (originalSize / 500) : 1.0;

    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
    bitmapOptions.inDither = true;//optional
    bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
    input = context.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
    input.close();
    return bitmap;
}

private static int getPowerOfTwoForSampleRatio(double ratio) {
    int k = Integer.highestOneBit((int) Math.floor(ratio));
    if (k == 0) return 1;
    else return k;
}

public static File compressFile(File file, Context context) {
    try {

        // BitmapFactory options to downsize the image
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        o.inSampleSize = 6;
        // factor of downsizing the image

        FileInputStream inputStream = new FileInputStream(file);
        //Bitmap selectedBitmap = null;
        BitmapFactory.decodeStream(inputStream, null, o);
        inputStream.close();

        // The new size we want to scale to
        final int REQUIRED_SIZE = 75;

        // Find the correct scale value. It should be the power of 2.
        int scale = 1;
        while (o.outWidth / scale / 2 >= REQUIRED_SIZE &&
                o.outHeight / scale / 2 >= REQUIRED_SIZE) {
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        inputStream = new FileInputStream(file);

        Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2);
        inputStream.close();

        // here i override the original image file
        file.createNewFile();
        FileOutputStream outputStream = new FileOutputStream(file);

        selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);

        return file;
    } catch (Exception e) {
        return null;
    }
}
} 



ImageCompression.compressFile(YourFile, this);
ImageCompression.getThumbnail(YourUri, this);
like image 152
Veeresh Charantimath Avatar answered Feb 06 '26 04:02

Veeresh Charantimath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!