Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link

ImageCompressor in Android

ImageCompressor in Android


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageCompressor {

    private static final String TAG = "ImageCompressor";
    private static final int MAX_IMAGE_SIZE = 1000;

    /**
     * Compresses the given image file and saves it to the same location.
     *
     * @param imageFile The image file to compress.
     * @return true if the image was successfully compressed and saved, false otherwise.
     */
    public static boolean compressImage(File imageFile) {
        if (imageFile == null || !imageFile.exists()) {
            Log.e(TAG, "Invalid image file provided.");
            return false;
        }

        Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());

        // Scale down the image if necessary
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scale = Math.min(1f, Math.max((float) MAX_IMAGE_SIZE / width, (float) MAX_IMAGE_SIZE / height));
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        bitmap.recycle();

        try {
            FileOutputStream fos = new FileOutputStream(imageFile);
            fos.write(stream.toByteArray());
            fos.close();
            return true;
        } catch (IOException e) {
            Log.e(TAG, "Failed to compress image file.", e);
            return false;
        }
    }
}

        

Post a Comment