Centralize JPEG compression to a single function

This commit is contained in:
Pierre-Yves Nicolas
2026-03-22 18:09:12 +01:00
parent f336680a69
commit a9edfa2b87
3 changed files with 56 additions and 36 deletions

View File

@@ -15,8 +15,12 @@
package org.fairscan.imageprocessing
import org.opencv.core.Mat
import org.opencv.core.MatOfByte
import org.opencv.core.MatOfInt
import org.opencv.core.Size
import org.opencv.imgcodecs.Imgcodecs
import org.opencv.imgproc.Imgproc
import java.io.IOException
import kotlin.math.sqrt
fun resizeForMaxPixels(img: Mat, maxPixels: Double): Mat {
@@ -30,3 +34,19 @@ fun resizeForMaxPixels(img: Mat, maxPixels: Double): Mat {
Imgproc.resize(img, resizedImg, size, 0.0, 0.0, Imgproc.INTER_AREA)
return resizedImg
}
fun encodeJpeg(mat: Mat, jpegQuality: Int): ByteArray {
val params = MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, jpegQuality.coerceIn(0, 100))
val encoded = MatOfByte()
val ok = Imgcodecs.imencode(".jpg", mat, encoded, params)
params.release()
if (!ok) {
encoded.release()
throw IOException("Failed to encode JPEG")
}
val result = encoded.toArray()
encoded.release()
return result
}