feat: implement image compression utility and integrate it into maintenance repository sync logic

This commit is contained in:
Jhony Cesar
2026-08-05 15:05:13 -04:00
parent aeee13a0bd
commit 54a1fe669a
7 changed files with 374 additions and 23 deletions

View File

@@ -60,7 +60,12 @@ class FirebaseStorageSyncService(
}
try {
val fileUri = Uri.fromFile(photoFile)
val fileToUpload = if (photoFile.length() > 500 * 1024L) {
com.example.util.ImageCompressor.compressImageFile(photoFile, 500 * 1024L)
} else {
photoFile
}
val fileUri = Uri.fromFile(fileToUpload)
photoRef.putFile(fileUri).await()
val downloadUrl = photoRef.downloadUrl.await().toString()

View File

@@ -264,10 +264,29 @@ class MaintenanceRepository(
// 3. Fetch local history logs from Room DB
val localHistory = dao.getAllHistoryList()
// 4. Reconcile and merge all history logs
val allHistories = (remoteHistory + localHistory)
.distinctBy { "${it.numeroOs}_${it.timestamp}" }
.sortedByDescending { it.timestamp }
// 4. Reconcile and merge all history logs prioritizing entries with remote URLs (http/https)
val localHistoryMap = localHistory.associateBy { "${it.numeroOs}_${it.timestamp}" }
val remoteHistoryMap = remoteHistory.associateBy { "${it.numeroOs}_${it.timestamp}" }
val allKeys = (localHistoryMap.keys + remoteHistoryMap.keys).toSet()
val allHistories = allKeys.map { key ->
val localItem = localHistoryMap[key]
val remoteItem = remoteHistoryMap[key]
when {
localItem != null && remoteItem != null -> {
val localHasUrl = localItem.fotoPath?.let { it.contains("http://") || it.contains("https://") } == true
val remoteHasUrl = remoteItem.fotoPath?.let { it.contains("http://") || it.contains("https://") } == true
if (localHasUrl && !remoteHasUrl) {
localItem
} else {
remoteItem
}
}
localItem != null -> localItem
else -> remoteItem!!
}
}.sortedByDescending { it.timestamp }
// 5. Update local Room DB with any remote history logs we don't have
val localHistoryKeys = localHistory.map { "${it.numeroOs}_${it.timestamp}" }.toSet()
@@ -282,17 +301,29 @@ class MaintenanceRepository(
// 6. For each remote activity, determine its current state based on the latest history log
val reconciledActivities = remoteActivities.map { activity ->
val osHistory = allHistories.filter { it.numeroOs == activity.numeroOs }
val localAct = dao.getActivityByOsOneShot(activity.numeroOs)
val localFotoPath = localAct?.fotoPath
val localHasRemoteUrl = localFotoPath?.let { it.contains("http://") || it.contains("https://") } == true
if (osHistory.isNotEmpty()) {
val latestLog = osHistory.first() // sorted descending, so first is latest
val finalFotoPath = if (localHasRemoteUrl && latestLog.fotoPath?.startsWith("http") != true) {
localFotoPath
} else {
latestLog.fotoPath ?: activity.fotoPath
}
activity.copy(
percentualExecucao = latestLog.percentualNovo,
observacoes = latestLog.observacao ?: activity.observacoes,
fotoPath = latestLog.fotoPath ?: activity.fotoPath,
fotoPath = finalFotoPath,
synced = true,
lastUpdated = latestLog.timestamp
)
} else {
activity.copy(synced = true)
activity.copy(
fotoPath = if (localHasRemoteUrl) localFotoPath else activity.fotoPath,
synced = true
)
}
}
@@ -452,12 +483,12 @@ class MaintenanceRepository(
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
val targetFile = java.io.File(photosDir, "OS_${sanitizedOs}_${timestamp}.jpg")
context.contentResolver.openInputStream(uri)?.use { input ->
targetFile.outputStream().use { output ->
input.copyTo(output)
}
}
return targetFile.absolutePath
return com.example.util.ImageCompressor.compressUriToJpegFile(
context = context,
uri = uri,
targetFile = targetFile,
maxSizeBytes = 500 * 1024L
).absolutePath
}
fun createTempCameraPhotoUri(osNumber: String): Pair<Uri, String> {
@@ -486,7 +517,8 @@ class MaintenanceRepository(
val file = java.io.File(trimmed)
if (file.exists()) {
try {
val result = firebaseStorageSyncService.uploadPhoto(file, history.numeroOs)
val compressedFile = com.example.util.ImageCompressor.compressImageFile(file, 500 * 1024L)
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, history.numeroOs)
changed = true
result.downloadUrl
} catch (e: Exception) {

View File

@@ -0,0 +1,241 @@
package com.example.util
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.Build
import android.util.Log
import android.media.ExifInterface
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
object ImageCompressor {
private const val TAG = "ImageCompressor"
private const val MAX_DIMENSION = 1920
private const val DEFAULT_MAX_SIZE_BYTES = 500 * 1024L // 500 KB
/**
* Compresses an image from a [Uri] (supporting JPEG, PNG, HEIC/HEIF, WEBP)
* and saves it to [targetFile] as JPEG guaranteed to be <= [maxSizeBytes].
*/
fun compressUriToJpegFile(
context: Context,
uri: Uri,
targetFile: File,
maxSizeBytes: Long = DEFAULT_MAX_SIZE_BYTES
): File {
return try {
val inputStream = context.contentResolver.openInputStream(uri)
?: throw IllegalArgumentException("Não foi possível abrir o Uri: $uri")
// Read orientation if available
val orientation = getOrientationFromUri(context, uri)
val bitmap = decodeBitmapFromStream(context, uri, inputStream, MAX_DIMENSION, MAX_DIMENSION)
?: throw IllegalStateException("Falha ao decodificar imagem a partir de Uri: $uri")
val rotatedBitmap = rotateBitmap(bitmap, orientation)
compressBitmapToFile(rotatedBitmap, targetFile, maxSizeBytes)
} catch (e: Exception) {
Log.e(TAG, "Erro ao comprimir imagem a partir de Uri $uri: ${e.message}", e)
// Fallback: try direct stream copy if decode fails
try {
context.contentResolver.openInputStream(uri)?.use { input ->
targetFile.outputStream().use { output ->
input.copyTo(output)
}
}
} catch (fallbackEx: Exception) {
Log.e(TAG, "Erro no fallback de cópia de imagem: ${fallbackEx.message}", fallbackEx)
}
targetFile
}
}
/**
* Compresses an existing local [inputFile] (supporting JPEG, PNG, HEIC/HEIF)
* so that it is guaranteed to be <= [maxSizeBytes]. Returns the compressed file (or original if already <= maxSizeBytes).
*/
fun compressImageFile(
inputFile: File,
maxSizeBytes: Long = DEFAULT_MAX_SIZE_BYTES
): File {
if (!inputFile.exists()) return inputFile
// If file is already smaller than maxSizeBytes and is a standard JPG, return as is
if (inputFile.length() <= maxSizeBytes && inputFile.extension.lowercase() in listOf("jpg", "jpeg")) {
return inputFile
}
return try {
val orientation = getOrientationFromFile(inputFile)
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeFile(inputFile.absolutePath, options)
val sampleSize = calculateInSampleSize(options, MAX_DIMENSION, MAX_DIMENSION)
val decodeOptions = BitmapFactory.Options().apply {
inSampleSize = sampleSize
}
val decodedBitmap = BitmapFactory.decodeFile(inputFile.absolutePath, decodeOptions)
?: return inputFile
val rotatedBitmap = rotateBitmap(decodedBitmap, orientation)
val compressedFile = compressBitmapToFile(rotatedBitmap, inputFile, maxSizeBytes)
compressedFile
} catch (e: Exception) {
Log.e(TAG, "Erro ao comprimir arquivo de imagem ${inputFile.name}: ${e.message}", e)
inputFile
}
}
private fun decodeBitmapFromStream(
context: Context,
uri: Uri,
inputStream: InputStream,
reqWidth: Int,
reqHeight: Int
): Bitmap? {
return try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val source = android.graphics.ImageDecoder.createSource(context.contentResolver, uri)
android.graphics.ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
val width = info.size.width
val height = info.size.height
if (width > reqWidth || height > reqHeight) {
val scale = Math.min(reqWidth.toFloat() / width, reqHeight.toFloat() / height)
decoder.setTargetSize((width * scale).toInt(), (height * scale).toInt())
}
decoder.allocator = android.graphics.ImageDecoder.ALLOCATOR_SOFTWARE
}
} else {
val bytes = inputStream.readBytes()
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight)
options.inJustDecodeBounds = false
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
}
} catch (e: Exception) {
Log.w(TAG, "Falha na decodificação primária de bitmap: ${e.message}. Tentando decodeStream nativo.")
BitmapFactory.decodeStream(inputStream)
} finally {
try { inputStream.close() } catch (_: Exception) {}
}
}
private fun compressBitmapToFile(
originalBitmap: Bitmap,
targetFile: File,
maxSizeBytes: Long
): File {
var currentBitmap = originalBitmap
var quality = 85
var stream = ByteArrayOutputStream()
currentBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream)
// Iterative reduction loop
while (stream.size() > maxSizeBytes && quality > 20) {
stream.reset()
quality -= 10
currentBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream)
}
// If quality reached lower limit and still larger than maxSizeBytes, scale dimensions down
while (stream.size() > maxSizeBytes && currentBitmap.width > 300 && currentBitmap.height > 300) {
stream.reset()
val newWidth = (currentBitmap.width * 0.85).toInt()
val newHeight = (currentBitmap.height * 0.85).toInt()
val scaledBitmap = Bitmap.createScaledBitmap(currentBitmap, newWidth, newHeight, true)
if (currentBitmap != originalBitmap) {
currentBitmap.recycle()
}
currentBitmap = scaledBitmap
quality = 70
currentBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream)
}
FileOutputStream(targetFile).use { out ->
out.write(stream.toByteArray())
}
if (currentBitmap != originalBitmap) {
currentBitmap.recycle()
}
originalBitmap.recycle()
Log.d(TAG, "Foto compactada com sucesso: ${targetFile.name}, tamanho final: ${targetFile.length() / 1024} KB")
return targetFile
}
private fun getOrientationFromFile(file: File): Int {
return try {
val exif = ExifInterface(file.absolutePath)
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
} catch (e: Exception) {
ExifInterface.ORIENTATION_UNDEFINED
}
}
private fun getOrientationFromUri(context: Context, uri: Uri): Int {
return try {
context.contentResolver.openInputStream(uri)?.use { stream ->
val exif = ExifInterface(stream)
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
} ?: ExifInterface.ORIENTATION_UNDEFINED
} catch (e: Exception) {
ExifInterface.ORIENTATION_UNDEFINED
}
}
private fun rotateBitmap(bitmap: Bitmap, orientation: Int): Bitmap {
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1f, 1f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1f, -1f)
else -> return bitmap
}
return try {
val rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
if (rotated != bitmap) {
bitmap.recycle()
}
rotated
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM ao rotacionar bitmap: ${e.message}")
bitmap
}
}
private fun calculateInSampleSize(
options: BitmapFactory.Options,
reqWidth: Int,
reqHeight: Int
): Int {
val (height: Int, width: Int) = options.run { outHeight to outWidth }
var inSampleSize = 1
if (height > reqHeight || width > reqWidth) {
val halfHeight: Int = height / 2
val halfWidth: Int = width / 2
while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
inSampleSize *= 2
}
}
return inSampleSize
}
}

View File

@@ -0,0 +1,71 @@
package com.example.util
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import androidx.test.core.app.ApplicationProvider
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
import java.io.FileOutputStream
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ImageCompressorTest {
@get:Rule
val tempFolder = TemporaryFolder()
@Test
fun `compressImageFile should compress large bitmap file to under 500KB`() {
val largeFile = tempFolder.newFile("large_test_image.jpg")
// Create a large 3000x3000 bitmap
val bitmap = Bitmap.createBitmap(3000, 3000, Bitmap.Config.ARGB_8888)
val canvas = android.graphics.Canvas(bitmap)
canvas.drawColor(Color.BLUE)
FileOutputStream(largeFile).use { out ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
}
val compressedFile = ImageCompressor.compressImageFile(largeFile, 500 * 1024L)
assertTrue("File should exist", compressedFile.exists())
assertTrue(
"Compressed file size (${compressedFile.length() / 1024} KB) should be <= 500 KB",
compressedFile.length() <= 500 * 1024L
)
}
@Test
fun `compressUriToJpegFile should compress uri content to under 500KB`() {
val context = ApplicationProvider.getApplicationContext<Context>()
val sourceFile = tempFolder.newFile("source_image.png")
val bitmap = Bitmap.createBitmap(2500, 2500, Bitmap.Config.ARGB_8888)
val canvas = android.graphics.Canvas(bitmap)
canvas.drawColor(Color.RED)
FileOutputStream(sourceFile).use { out ->
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
}
val uri = Uri.fromFile(sourceFile)
val targetFile = tempFolder.newFile("target_compressed.jpg")
val resultFile = ImageCompressor.compressUriToJpegFile(context, uri, targetFile, 500 * 1024L)
assertTrue("Target file should exist", resultFile.exists())
assertTrue(
"Target file size (${resultFile.length() / 1024} KB) should be <= 500 KB",
resultFile.length() <= 500 * 1024L
)
}
}