Android Compress Image And Save To Public Directory


public class ImageCompressor {
    public final int MAX_DIMENSION = 720;

    // public String compressAndCopy(Context context, Uri imageUri) { TODO }

    public String compressImage(Context context, String filePath) {
        try {
            String fileName = getFileNameFromPath(filePath);
            // Decode image from file path
            Bitmap bitmap = decodeBitmapFromFile(filePath);

            if (bitmap == null) {
                System.out.println("ImageCompressor Failed to decode bitmap from file path.");
                return filePath;
            }

            // Calculate scale factor to fit within MAX_DIMENSION pixels width or height
            float scaleFactor = calculateScaleFactor(bitmap.getWidth(), bitmap.getHeight());

            Bitmap resizedBitmap;
            if (scaleFactor == 1.0) {
                resizedBitmap = bitmap;
            } else {
                resizedBitmap = resizeBitmap(bitmap, scaleFactor);
            }
            return saveBitmapToFile(context, resizedBitmap, fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return filePath;
        }
    }

    private Bitmap decodeBitmapFromFile(String filePath) throws IOException {
        return BitmapFactory.decodeFile(filePath);
    }

    private float calculateScaleFactor(int width, int height) {
        float scaleFactor = 1.0f;

        if (width > MAX_DIMENSION || height > MAX_DIMENSION) {
            float widthScale = (float) MAX_DIMENSION / width;
            float heightScale = (float) MAX_DIMENSION / height;
            scaleFactor = Math.min(widthScale, heightScale);
        }

        return scaleFactor;
    }

    private Bitmap resizeBitmap(Bitmap bitmap, float scaleFactor) {
        int newWidth = Math.round(bitmap.getWidth() * scaleFactor);
        int newHeight = Math.round(bitmap.getHeight() * scaleFactor);
        return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
    }

    private String getFileNameFromPath(String filePath) {
        // Split the file path using the file separator ("/" for Unix-like systems)
        String[] parts = filePath.split("/");
        // The last part will be the file name
        return parts[parts.length - 1];
    }

    // Utility method to save bitmap to a file
    // Save compressed image to public storage directory (Environment.DIRECTORY_PICTURES)
    // You can change the directory as needed ex : Environment.DIRECTORY_DOCUMENTS
    public String saveBitmapToFile(Context context, Bitmap bitmap, String fileName) {
        File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        // You can change the name of the directory as needed
        File directory = new File(picturesDirectory, "MyPicDirectory");
        if (!directory.exists()) directory.mkdirs();
        File outputFile = new File(directory, fileName);
        try (OutputStream out = new FileOutputStream(outputFile)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            return outputFile.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Komentar