FileCompressionHelper

Compresses image files before uploading them to the server, keeping the quality loss to a minimum.

Files that are already below the target size and in a format the server accepts are returned untouched. Otherwise the image is re-encoded at a fixed quality and the size is reduced by downscaling: every attempt is measured and the next scale is predicted from that measurement, so the result lands just below the target instead of well under it.

Note that only JPEG and PNG are produced, because those are the only formats that the platform can encode and the server accepts. Anything else that can be decoded (webp, heif, bmp, gif...) is converted, and the caller is responsible for exposing the resulting file with the extension it now has: the content type is derived from the name, and it must agree with the actual bytes.

Functions

Link copied to clipboard
fun compressFile(fileToCompress: File, targetSizeBytes: Long = TARGET_SIZE_BYTES): File

Compress an image file so that its encoded size does not exceed targetSizeBytes. The aspect ratio and the EXIF orientation are always preserved.