Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

Image editor engine: op model, adjustments, presets, draw/text/watermark, bg removal, IO

Chethan6166bb4a558f97c
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/Adjustments.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/Adjustments.kt
new file mode 100644
index 0000000..288ed3c
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/Adjustments.kt
@@ -0,0 +1,175 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.ColorMatrix
+import android.graphics.ColorMatrixColorFilter
+import android.graphics.Paint
+import android.graphics.PointF
+import jp.co.cyberagent.android.gpuimage.GPUImage
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilterGroup
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageGammaFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageSharpenFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageVibranceFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageVignetteFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageWhiteBalanceFilter
+import kotlin.math.cos
+import kotlin.math.pow
+import kotlin.math.sin
+
+/**
+ * Tonal adjustments. The slider range is symmetric around [default] where that makes sense.
+ * Colour-matrix adjustments are applied on the CPU in one pass; the rest go through GPUImage
+ * (selection of filters follows ImageToolbox's feature/filters/data/model — Apache-2.0).
+ */
+enum class Adjust(val min: Float, val max: Float, val default: Float, val gpu: Boolean) {
+ Brightness(-100f, 100f, 0f, false),
+ Contrast(-100f, 100f, 0f, false),
+ Saturation(-100f, 100f, 0f, false),
+ Exposure(-100f, 100f, 0f, false),
+ Highlights(-100f, 100f, 0f, false),
+ Shadows(-100f, 100f, 0f, false),
+ Temperature(-100f, 100f, 0f, true),
+ Tint(-100f, 100f, 0f, true),
+ Vibrance(-100f, 100f, 0f, true),
+ Hue(-180f, 180f, 0f, false),
+ Gamma(-100f, 100f, 0f, true),
+ Sharpen(0f, 100f, 0f, true),
+ Vignette(0f, 100f, 0f, true);
+}
+
+object AdjustRenderer {
+
+ fun colorMatrix(values: Map<Adjust, Float>): ColorMatrix? {
+ fun v(a: Adjust) = values[a] ?: a.default
+ val b = v(Adjust.Brightness)
+ val c = v(Adjust.Contrast)
+ val s = v(Adjust.Saturation)
+ val e = v(Adjust.Exposure)
+ val h = v(Adjust.Hue)
+ if (b == 0f && c == 0f && s == 0f && e == 0f && h == 0f) return null
+ val m = ColorMatrix()
+ if (e != 0f) {
+ val k = 2f.pow(e / 50f) // ±2 stops
+ m.postConcat(scale(k))
+ }
+ if (s != 0f) m.postConcat(ColorMatrix().apply { setSaturation(1f + s / 100f) })
+ if (h != 0f) m.postConcat(hueMatrix(h))
+ if (c != 0f) {
+ val k = if (c > 0) 1f + c / 50f else 1f + c / 125f
+ val t = (1f - k) * 127.5f
+ m.postConcat(ColorMatrix(floatArrayOf(k, 0f, 0f, 0f, t, 0f, k, 0f, 0f, t, 0f, 0f, k, 0f, t, 0f, 0f, 0f, 1f, 0f)))
+ }
+ if (b != 0f) {
+ val t = b * 1.1f
+ m.postConcat(ColorMatrix(floatArrayOf(1f, 0f, 0f, 0f, t, 0f, 1f, 0f, 0f, t, 0f, 0f, 1f, 0f, t, 0f, 0f, 0f, 1f, 0f)))
+ }
+ return m
+ }
+
+ fun gpuFilters(values: Map<Adjust, Float>): List<GPUImageFilter> {
+ fun v(a: Adjust) = values[a] ?: a.default
+ val out = mutableListOf<GPUImageFilter>()
+ val temp = v(Adjust.Temperature)
+ val tint = v(Adjust.Tint)
+ if (temp != 0f || tint != 0f) out += GPUImageWhiteBalanceFilter(5000f + temp * 20f, tint)
+ val vib = v(Adjust.Vibrance)
+ if (vib != 0f) out += GPUImageVibranceFilter(vib / 50f)
+ val g = v(Adjust.Gamma)
+ if (g != 0f) out += GPUImageGammaFilter(if (g > 0) 1f - g / 200f else 1f - g / 50f)
+ val sp = v(Adjust.Sharpen)
+ if (sp != 0f) out += GPUImageSharpenFilter(sp / 25f)
+ val vg = v(Adjust.Vignette)
+ if (vg != 0f) out += GPUImageVignetteFilter(
+ PointF(0.5f, 0.5f), floatArrayOf(0f, 0f, 0f), 0.75f - vg / 250f, 1f
+ )
+ return out
+ }
+
+ fun apply(context: Context, src: Bitmap, values: Map<Adjust, Float>): Bitmap {
+ var cur = src
+ colorMatrix(values)?.let { cur = applyMatrix(cur, it) }
+ val hi = values[Adjust.Highlights] ?: 0f
+ val sh = values[Adjust.Shadows] ?: 0f
+ if (hi != 0f || sh != 0f) {
+ val next = applyToneLut(cur, toneLut(sh / 100f, hi / 100f))
+ if (cur !== src) cur.recycle()
+ cur = next
+ }
+ val gpu = gpuFilters(values)
+ if (gpu.isNotEmpty()) {
+ val filtered = GpuRunner.apply(context, cur, if (gpu.size == 1) gpu[0] else GPUImageFilterGroup(gpu))
+ if (filtered != null) {
+ if (cur !== src) cur.recycle()
+ cur = filtered
+ }
+ }
+ return cur
+ }
+
+ fun applyMatrix(src: Bitmap, m: ColorMatrix): Bitmap {
+ val out = Bitmap.createBitmap(src.width, src.height, Bitmap.Config.ARGB_8888)
+ Canvas(out).drawBitmap(src, 0f, 0f, Paint(Paint.FILTER_BITMAP_FLAG).apply { colorFilter = ColorMatrixColorFilter(m) })
+ return out
+ }
+
+ /** Shadow / highlight tone curve: lifts or crushes the low / high end independently. */
+ private fun toneLut(shadows: Float, highlights: Float): IntArray = IntArray(256) { i ->
+ val x = i / 255f
+ val y = x + shadows * 2.2f * x * (1 - x) * (1 - x) + highlights * 2.2f * x * x * (1 - x)
+ (y.coerceIn(0f, 1f) * 255f + 0.5f).toInt()
+ }
+
+ private fun applyToneLut(src: Bitmap, lut: IntArray): Bitmap {
+ val w = src.width
+ val h = src.height
+ val out = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ val row = IntArray(w)
+ for (y in 0 until h) {
+ src.getPixels(row, 0, w, 0, y, w, 1)
+ for (x in 0 until w) {
+ val p = row[x]
+ row[x] = (p and -0x1000000) or (lut[p shr 16 and 0xFF] shl 16) or
+ (lut[p shr 8 and 0xFF] shl 8) or lut[p and 0xFF]
+ }
+ out.setPixels(row, 0, w, 0, y, w, 1)
+ }
+ return out
+ }
+
+ private fun scale(k: Float) = ColorMatrix(floatArrayOf(k, 0f, 0f, 0f, 0f, 0f, k, 0f, 0f, 0f, 0f, 0f, k, 0f, 0f, 0f, 0f, 0f, 1f, 0f))
+
+ /** Luminance-preserving hue rotation. */
+ fun hueMatrix(degrees: Float): ColorMatrix {
+ val r = Math.toRadians(degrees.toDouble())
+ val c = cos(r).toFloat()
+ val s = sin(r).toFloat()
+ val lr = 0.213f; val lg = 0.715f; val lb = 0.072f
+ return ColorMatrix(floatArrayOf(
+ lr + c * (1 - lr) + s * (-lr), lg + c * (-lg) + s * (-lg), lb + c * (-lb) + s * (1 - lb), 0f, 0f,
+ lr + c * (-lr) + s * 0.143f, lg + c * (1 - lg) + s * 0.140f, lb + c * (-lb) + s * (-0.283f), 0f, 0f,
+ lr + c * (-lr) + s * (-(1 - lr)), lg + c * (-lg) + s * lg, lb + c * (1 - lb) + s * lb, 0f, 0f,
+ 0f, 0f, 0f, 1f, 0f
+ ))
+ }
+}
+
+/**
+ * Runs a GPUImage filter off-screen. GPUImage creates its own EGL context on the calling thread,
+ * so callers must stay on the editor's single render thread. Returns null if GL fails (e.g. the
+ * bitmap exceeds GL_MAX_TEXTURE_SIZE) so callers can fall back gracefully.
+ */
+object GpuRunner {
+ fun apply(context: Context, src: Bitmap, filter: GPUImageFilter): Bitmap? = runCatching {
+ val input = if (src.config == Bitmap.Config.ARGB_8888 && !src.isRecycled) src
+ else src.copy(Bitmap.Config.ARGB_8888, false)
+ val gpu = GPUImage(context.applicationContext)
+ gpu.setFilter(filter)
+ val out = gpu.getBitmapWithFilterApplied(input, false)
+ gpu.deleteImage()
+ if (input !== src) input.recycle()
+ out
+ }.getOrNull()
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemover.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemover.kt
new file mode 100644
index 0000000..f6be5b7
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemover.kt
@@ -0,0 +1,83 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.os.Build
+import com.google.mlkit.vision.common.InputImage
+import com.google.mlkit.vision.segmentation.subject.SubjectSegmentation
+import com.google.mlkit.vision.segmentation.subject.SubjectSegmenterOptions
+import kotlinx.coroutines.suspendCancellableCoroutine
+import kotlin.coroutines.resume
+
+/**
+ * Produces a subject mask for automatic background removal. Kept behind an interface so a FOSS
+ * build flavour can provide a different (or no) implementation without touching the editor.
+ */
+interface BackgroundRemover {
+ /** False when the device / build can't run automatic removal at all. */
+ val isAvailable: Boolean
+
+ /**
+ * Returns an [Bitmap.Config.ALPHA_8] mask the size of [image] (opaque = keep), or a failure
+ * whose message is user-presentable.
+ */
+ suspend fun segment(image: Bitmap): Result<Bitmap>
+
+ companion object {
+ fun create(context: Context): BackgroundRemover = MlKitBackgroundRemover(context.applicationContext)
+ }
+}
+
+/** Google Play services ML Kit subject segmentation (model is fetched by Play services). */
+private class MlKitBackgroundRemover(private val context: Context) : BackgroundRemover {
+
+ override val isAvailable: Boolean
+ get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && hasPlayServices()
+
+ private fun hasPlayServices(): Boolean = runCatching {
+ context.packageManager.getPackageInfo("com.google.android.gms", 0); true
+ }.getOrDefault(false)
+
+ override suspend fun segment(image: Bitmap): Result<Bitmap> {
+ if (!isAvailable) return Result.failure(IllegalStateException("Background removal isn't available on this device."))
+ return runCatching { segmentImpl(image) }
+ }
+
+ private suspend fun segmentImpl(image: Bitmap): Bitmap {
+ val options = SubjectSegmenterOptions.Builder()
+ .enableForegroundConfidenceMask()
+ .build()
+ val client = SubjectSegmentation.getClient(options)
+ try {
+ val input = InputImage.fromBitmap(image, 0)
+ val result = suspendCancellableCoroutine { cont ->
+ client.process(input)
+ .addOnSuccessListener { cont.resume(Result.success(it)) }
+ .addOnFailureListener { cont.resume(Result.failure(it)) }
+ }.getOrElse { e ->
+ val msg = e.message.orEmpty()
+ throw IllegalStateException(
+ if (msg.contains("download", true) || msg.contains("module", true))
+ "The background-removal model is still downloading. Try again in a moment."
+ else "Couldn't detect a subject in this image."
+ )
+ }
+ val buffer = result.foregroundConfidenceMask
+ ?: throw IllegalStateException("Couldn't detect a subject in this image.")
+ val w = image.width
+ val h = image.height
+ buffer.rewind()
+ val pixels = IntArray(w * h)
+ for (i in 0 until w * h) {
+ val c = buffer.get().coerceIn(0f, 1f)
+ pixels[i] = ((c * 255f).toInt() shl 24)
+ }
+ val argb = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)
+ val mask = argb.extractAlpha()
+ argb.recycle()
+ return mask
+ } finally {
+ client.close()
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BlurUtils.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BlurUtils.kt
new file mode 100644
index 0000000..477dc85
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BlurUtils.kt
@@ -0,0 +1,196 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.HardwareRenderer
+import android.graphics.Paint
+import android.graphics.PixelFormat
+import android.graphics.RenderEffect
+import android.graphics.RenderNode
+import android.graphics.Shader
+import android.hardware.HardwareBuffer
+import android.media.ImageReader
+import android.os.Build
+import androidx.annotation.RequiresApi
+import androidx.core.graphics.scale
+import kotlin.math.max
+import kotlin.math.roundToInt
+
+/** Blur / pixelate helpers used by the blur & pixelate brushes (no native libraries). */
+object BlurUtils {
+
+ /** Gaussian-looking blur. API 31+: RenderEffect via HardwareRenderer; otherwise stack blur. */
+ fun blur(src: Bitmap, radiusPx: Float): Bitmap {
+ val r = radiusPx.coerceAtLeast(1f)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ runCatching { renderEffectBlur(src, r) }.getOrNull()?.let { return it }
+ }
+ // Downscale first so large radii stay cheap, then stack blur and scale back.
+ val factor = max(1f, r / 8f)
+ val sw = max(1, (src.width / factor).roundToInt())
+ val sh = max(1, (src.height / factor).roundToInt())
+ val small = if (factor > 1f) src.scale(sw, sh, true) else src.copy(Bitmap.Config.ARGB_8888, true)
+ stackBlur(small, (r / factor).roundToInt().coerceIn(1, 254))
+ return if (factor > 1f) small.scale(src.width, src.height, true).also { small.recycle() } else small
+ }
+
+ fun pixelate(src: Bitmap, blockPx: Float): Bitmap {
+ val b = blockPx.coerceAtLeast(2f)
+ val sw = max(1, (src.width / b).roundToInt())
+ val sh = max(1, (src.height / b).roundToInt())
+ val small = src.scale(sw, sh, true)
+ val out = Bitmap.createBitmap(src.width, src.height, Bitmap.Config.ARGB_8888)
+ Canvas(out).drawBitmap(small, null, android.graphics.Rect(0, 0, out.width, out.height), Paint())
+ small.recycle()
+ return out
+ }
+
+ @RequiresApi(Build.VERSION_CODES.S)
+ private fun renderEffectBlur(src: Bitmap, radius: Float): Bitmap? {
+ val w = src.width
+ val h = src.height
+ val reader = ImageReader.newInstance(
+ w, h, PixelFormat.RGBA_8888, 1,
+ HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT
+ )
+ val renderer = HardwareRenderer()
+ val node = RenderNode("editorBlur")
+ try {
+ renderer.setSurface(reader.surface)
+ renderer.setContentRoot(node)
+ node.setPosition(0, 0, w, h)
+ node.setRenderEffect(RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP))
+ val canvas = node.beginRecording()
+ canvas.drawBitmap(src, 0f, 0f, null)
+ node.endRecording()
+ renderer.createRenderRequest().setWaitForPresent(true).syncAndDraw()
+ val image = reader.acquireNextImage() ?: return null
+ image.use {
+ val hb = it.hardwareBuffer ?: return null
+ hb.use { buffer ->
+ val hw = Bitmap.wrapHardwareBuffer(buffer, null) ?: return null
+ val out = hw.copy(Bitmap.Config.ARGB_8888, true)
+ hw.recycle()
+ return out
+ }
+ }
+ } finally {
+ node.discardDisplayList()
+ renderer.destroy()
+ reader.close()
+ }
+ }
+
+ /**
+ * Stack Blur v1.0 by Mario Klingemann (public-domain algorithm), in-place on [bitmap].
+ */
+ fun stackBlur(bitmap: Bitmap, radius: Int) {
+ if (radius < 1) return
+ val w = bitmap.width
+ val h = bitmap.height
+ val pix = IntArray(w * h)
+ bitmap.getPixels(pix, 0, w, 0, 0, w, h)
+ val wm = w - 1
+ val hm = h - 1
+ val wh = w * h
+ val div = radius + radius + 1
+ val r = IntArray(wh); val g = IntArray(wh); val b = IntArray(wh); val a = IntArray(wh)
+ var rsum: Int; var gsum: Int; var bsum: Int; var asum: Int
+ var x: Int; var y: Int; var i: Int; var p: Int; var yp: Int; var yi: Int
+ val vmin = IntArray(max(w, h))
+ var divsum = (div + 1) shr 1
+ divsum *= divsum
+ val dv = IntArray(256 * divsum) { it / divsum }
+ yi = 0
+ var yw = 0
+ val stack = Array(div) { IntArray(4) }
+ var stackpointer: Int
+ var stackstart: Int
+ var sir: IntArray
+ var rbs: Int
+ val r1 = radius + 1
+ var routsum: Int; var goutsum: Int; var boutsum: Int; var aoutsum: Int
+ var rinsum: Int; var ginsum: Int; var binsum: Int; var ainsum: Int
+ y = 0
+ while (y < h) {
+ rinsum = 0; ginsum = 0; binsum = 0; ainsum = 0
+ routsum = 0; goutsum = 0; boutsum = 0; aoutsum = 0
+ rsum = 0; gsum = 0; bsum = 0; asum = 0
+ i = -radius
+ while (i <= radius) {
+ p = pix[yi + minOf(wm, max(i, 0))]
+ sir = stack[i + radius]
+ sir[0] = p and 0xff0000 shr 16; sir[1] = p and 0x00ff00 shr 8; sir[2] = p and 0x0000ff; sir[3] = p ushr 24
+ rbs = r1 - kotlin.math.abs(i)
+ rsum += sir[0] * rbs; gsum += sir[1] * rbs; bsum += sir[2] * rbs; asum += sir[3] * rbs
+ if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; ainsum += sir[3] }
+ else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; aoutsum += sir[3] }
+ i++
+ }
+ stackpointer = radius
+ x = 0
+ while (x < w) {
+ r[yi] = dv[rsum]; g[yi] = dv[gsum]; b[yi] = dv[bsum]; a[yi] = dv[asum]
+ rsum -= routsum; gsum -= goutsum; bsum -= boutsum; asum -= aoutsum
+ stackstart = stackpointer - radius + div
+ sir = stack[stackstart % div]
+ routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; aoutsum -= sir[3]
+ if (y == 0) vmin[x] = minOf(x + radius + 1, wm)
+ p = pix[yw + vmin[x]]
+ sir[0] = p and 0xff0000 shr 16; sir[1] = p and 0x00ff00 shr 8; sir[2] = p and 0x0000ff; sir[3] = p ushr 24
+ rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; ainsum += sir[3]
+ rsum += rinsum; gsum += ginsum; bsum += binsum; asum += ainsum
+ stackpointer = (stackpointer + 1) % div
+ sir = stack[stackpointer % div]
+ routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; aoutsum += sir[3]
+ rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; ainsum -= sir[3]
+ yi++
+ x++
+ }
+ yw += w
+ y++
+ }
+ x = 0
+ while (x < w) {
+ rinsum = 0; ginsum = 0; binsum = 0; ainsum = 0
+ routsum = 0; goutsum = 0; boutsum = 0; aoutsum = 0
+ rsum = 0; gsum = 0; bsum = 0; asum = 0
+ yp = -radius * w
+ i = -radius
+ while (i <= radius) {
+ yi = max(0, yp) + x
+ sir = stack[i + radius]
+ sir[0] = r[yi]; sir[1] = g[yi]; sir[2] = b[yi]; sir[3] = a[yi]
+ rbs = r1 - kotlin.math.abs(i)
+ rsum += r[yi] * rbs; gsum += g[yi] * rbs; bsum += b[yi] * rbs; asum += a[yi] * rbs
+ if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; ainsum += sir[3] }
+ else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; aoutsum += sir[3] }
+ if (i < hm) yp += w
+ i++
+ }
+ yi = x
+ stackpointer = radius
+ y = 0
+ while (y < h) {
+ pix[yi] = (dv[asum] shl 24) or (dv[rsum] shl 16) or (dv[gsum] shl 8) or dv[bsum]
+ rsum -= routsum; gsum -= goutsum; bsum -= boutsum; asum -= aoutsum
+ stackstart = stackpointer - radius + div
+ sir = stack[stackstart % div]
+ routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; aoutsum -= sir[3]
+ if (x == 0) vmin[y] = minOf(y + r1, hm) * w
+ p = x + vmin[y]
+ sir[0] = r[p]; sir[1] = g[p]; sir[2] = b[p]; sir[3] = a[p]
+ rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; ainsum += sir[3]
+ rsum += rinsum; gsum += ginsum; bsum += binsum; asum += ainsum
+ stackpointer = (stackpointer + 1) % div
+ sir = stack[stackpointer]
+ routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; aoutsum += sir[3]
+ rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; ainsum -= sir[3]
+ yi += w
+ y++
+ }
+ x++
+ }
+ bitmap.setPixels(pix, 0, w, 0, 0, w, h)
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/EditOps.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/EditOps.kt
new file mode 100644
index 0000000..1d3ac0a
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/EditOps.kt
@@ -0,0 +1,159 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.graphics.Bitmap
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropOutline
+
+/**
+ * One non-destructive step of an edit. The editor keeps an ordered list of these and replays
+ * it on a downscaled preview (interactive) or on the full-resolution source (export).
+ *
+ * Every coordinate is **normalised** (0..1 of the bitmap the op receives) and every stroke /
+ * text size is a fraction of that bitmap's short edge, so an op renders identically at any
+ * resolution.
+ */
+sealed interface EditOp
+
+/** Quarter turns + fine straighten + mirror. Straightening auto-zooms so no empty corners show. */
+data class TransformOp(
+ val quarterTurns: Int = 0,
+ val straighten: Float = 0f,
+ val flipH: Boolean = false,
+ val flipV: Boolean = false
+) : EditOp {
+ val isIdentity: Boolean
+ get() = Math.floorMod(quarterTurns, 4) == 0 && straighten == 0f && !flipH && !flipV
+}
+
+/** Rectangular crop (normalised) with an optional shape mask (circle, rounded, polygon…). */
+data class CropOp(
+ val rect: Rect,
+ val outline: CropOutline? = null
+) : EditOp
+
+/** Four corners (TL, TR, BR, BL; normalised) warped into an upright rectangle. */
+data class PerspectiveOp(val corners: List<Offset>) : EditOp
+
+/** A set of tonal adjustments; values are keyed by [Adjust] in that adjustment's own range. */
+data class AdjustOp(val values: Map<Adjust, Float>) : EditOp {
+ val isIdentity: Boolean get() = values.all { (k, v) -> v == k.default }
+}
+
+/** A look preset blended with the input by [intensity] (0..1). */
+data class FilterOp(val preset: FilterPreset, val intensity: Float = 1f) : EditOp
+
+/** Brush / shape strokes drawn on their own layer (so the eraser only removes drawing). */
+data class DrawOp(val strokes: List<DrawStroke>) : EditOp
+
+/** A single text overlay. */
+data class TextOp(val layer: TextLayer) : EditOp
+
+/**
+ * Background removal: an optional automatic subject mask (any resolution; it is scaled to the
+ * target) refined by manual erase / restore strokes.
+ */
+data class BackgroundOp(
+ val autoMask: Bitmap?,
+ val strokes: List<MaskStroke> = emptyList()
+) : EditOp {
+ // Bitmaps compare by identity, which is exactly what the render cache needs.
+}
+
+data class WatermarkOp(val params: WatermarkParams) : EditOp
+
+/** Target size in **full-resolution** pixels; the preview applies the same ratio. */
+data class ResizeOp(val width: Int, val height: Int) : EditOp
+
+// ── Draw model ─────────────────────────────────────────────────────────────────────────────
+
+enum class BrushKind { Pen, Highlighter, Neon, Eraser, Blur, Pixelate }
+
+enum class ShapeKind(val filled: Boolean = false, val sharp: Boolean = false) {
+ Free,
+ Line,
+ Arrow,
+ DoubleArrow,
+ LineArrow,
+ DoubleLineArrow,
+ Lasso(filled = true, sharp = true),
+ OutlinedRect(sharp = true),
+ Rect(filled = true, sharp = true),
+ OutlinedOval(sharp = true),
+ Oval(filled = true, sharp = true),
+ OutlinedTriangle,
+ Triangle(filled = true),
+ OutlinedPolygon,
+ Polygon(filled = true),
+ OutlinedStar,
+ Star(filled = true),
+ FloodFill(filled = true, sharp = true),
+ Spray(filled = true, sharp = true);
+
+ val isFreehand: Boolean get() = this == Free || this == Lasso || this == Spray ||
+ this == Arrow || this == DoubleArrow
+}
+
+data class DrawStroke(
+ val brush: BrushKind,
+ val shape: ShapeKind,
+ /** ARGB. */
+ val color: Int,
+ /** Stroke width as a fraction of the short edge. */
+ val width: Float,
+ /** 0..1 edge softness (blur mask / neon glow). */
+ val softness: Float = 0f,
+ val points: List<Offset>,
+ /** Blur radius / pixel size, as a fraction of the short edge (Blur / Pixelate brushes). */
+ val effectStrength: Float = 0.03f,
+ val floodTolerance: Float = 0.25f,
+ val polygonVertices: Int = 5,
+ val seed: Int = 0
+)
+
+data class MaskStroke(
+ val points: List<Offset>,
+ val width: Float,
+ val restore: Boolean
+)
+
+// ── Text model ─────────────────────────────────────────────────────────────────────────────
+
+enum class TextFont { Sans, Serif, Mono, Condensed, Cursive }
+
+data class TextLayer(
+ val text: String,
+ /** Centre, normalised. */
+ val center: Offset = Offset(0.5f, 0.5f),
+ /** Text size as a fraction of the short edge. */
+ val size: Float = 0.08f,
+ val rotation: Float = 0f,
+ val color: Int = 0xFFFFFFFF.toInt(),
+ val font: TextFont = TextFont.Sans,
+ val bold: Boolean = true,
+ val italic: Boolean = false,
+ /** ARGB or 0 for none. */
+ val outlineColor: Int = 0,
+ /** Outline width as a fraction of text size. */
+ val outlineWidth: Float = 0.08f,
+ /** ARGB or 0 for none. */
+ val backgroundColor: Int = 0,
+ val alpha: Float = 1f
+)
+
+// ── Watermark model ────────────────────────────────────────────────────────────────────────
+
+enum class WatermarkPosition { TopLeft, TopCenter, TopRight, CenterLeft, Center, CenterRight, BottomLeft, BottomCenter, BottomRight, Tiled }
+
+data class WatermarkParams(
+ val text: String = "",
+ val image: Bitmap? = null,
+ val color: Int = 0xFFFFFFFF.toInt(),
+ val alpha: Float = 0.5f,
+ /** Text size or image width as a fraction of the short edge. */
+ val size: Float = 0.06f,
+ val rotation: Float = 0f,
+ val position: WatermarkPosition = WatermarkPosition.BottomRight,
+ /** Margin / tile spacing as a fraction of the short edge. */
+ val spacing: Float = 0.04f
+)
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/EditRenderer.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/EditRenderer.kt
new file mode 100644
index 0000000..ce0e669
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/EditRenderer.kt
@@ -0,0 +1,130 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Matrix
+import android.graphics.Paint
+import android.graphics.PorterDuff
+import android.graphics.PorterDuffXfermode
+import android.graphics.Rect
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.asAndroidBitmap
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.unit.Density
+import androidx.compose.ui.unit.LayoutDirection
+import com.chethan616.clearpdf.imageeditor.engine.draw.ShapePaths
+import com.chethan616.clearpdf.imageeditor.engine.draw.StrokeRenderer
+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.crop.CropAgent
+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.RectCropShape
+import com.chethan616.clearpdf.imageeditor.thirdparty.freecorners.FreeCrop
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.max
+import kotlin.math.roundToInt
+import kotlin.math.sin
+
+/**
+ * Applies one [EditOp] to a bitmap. Every function returns a **new** bitmap and never recycles
+ * its input — the caller (render cache / exporter) owns lifetimes.
+ *
+ * @param resolutionScale ratio of the bitmap being rendered to the full-resolution source
+ * (1 for export, < 1 for the preview). Only [ResizeOp] needs it.
+ */
+class EditRenderer(private val context: Context) {
+
+ private val cropAgent = CropAgent()
+ private val density = Density(context)
+
+ fun apply(src: Bitmap, op: EditOp, resolutionScale: Float): Bitmap = when (op) {
+ is TransformOp -> transform(src, op)
+ is CropOp -> crop(src, op)
+ is PerspectiveOp -> FreeCrop.crop(src, op.corners.map { Offset(it.x * src.width, it.y * src.height) })
+ is AdjustOp -> AdjustRenderer.apply(context, src, op.values).let { if (it === src) src.copy(Bitmap.Config.ARGB_8888, true) else it }
+ is FilterOp -> FilterPreset.apply(context, src, op.preset, op.intensity)
+ is DrawOp -> StrokeRenderer.render(src, op.strokes)
+ is TextOp -> OverlayRenderer.drawText(src, op.layer)
+ is WatermarkOp -> OverlayRenderer.drawWatermark(src, op.params)
+ is BackgroundOp -> background(src, op)
+ is ResizeOp -> {
+ val w = max(1, (op.width * resolutionScale).roundToInt())
+ val h = max(1, (op.height * resolutionScale).roundToInt())
+ Bitmap.createScaledBitmap(src, w, h, true).let { if (it === src) src.copy(Bitmap.Config.ARGB_8888, true) else it }
+ }
+ }
+
+ fun transform(src: Bitmap, op: TransformOp): Bitmap {
+ val turns = Math.floorMod(op.quarterTurns, 4)
+ val swap = turns % 2 == 1
+ val outW = if (swap) src.height else src.width
+ val outH = if (swap) src.width else src.height
+ val theta = Math.toRadians(op.straighten.toDouble())
+ val c = abs(cos(theta)).toFloat()
+ val s = abs(sin(theta)).toFloat()
+ // Zoom so the rotated image still covers the whole frame (no empty corners).
+ val zoom = if (op.straighten == 0f) 1f else max((outW * c + outH * s) / outW, (outW * s + outH * c) / outH)
+ val m = Matrix().apply {
+ postTranslate(-src.width / 2f, -src.height / 2f)
+ postScale(if (op.flipH) -1f else 1f, if (op.flipV) -1f else 1f)
+ postRotate(turns * 90f + op.straighten)
+ postScale(zoom, zoom)
+ postTranslate(outW / 2f, outH / 2f)
+ }
+ val out = Bitmap.createBitmap(outW, outH, Bitmap.Config.ARGB_8888)
+ Canvas(out).drawBitmap(src, m, Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG))
+ return out
+ }
+
+ private fun crop(src: Bitmap, op: CropOp): Bitmap {
+ val l = (op.rect.left * src.width).roundToInt().coerceIn(0, src.width - 1)
+ val t = (op.rect.top * src.height).roundToInt().coerceIn(0, src.height - 1)
+ val r = (op.rect.right * src.width).roundToInt().coerceIn(l + 1, src.width)
+ val b = (op.rect.bottom * src.height).roundToInt().coerceIn(t + 1, src.height)
+ val out = Bitmap.createBitmap(r - l, b - t, Bitmap.Config.ARGB_8888)
+ Canvas(out).drawBitmap(src, Rect(l, t, r, b), Rect(0, 0, out.width, out.height), Paint(Paint.FILTER_BITMAP_FLAG))
+ val outline = op.outline ?: return out
+ if (outline is RectCropShape) return out
+ // Shape masks (circle, rounded, polygon, heart…) via the ported cropper's CropAgent.
+ val masked = cropAgent.crop(
+ imageBitmap = out.asImageBitmap(),
+ cropRect = androidx.compose.ui.geometry.Rect(0f, 0f, out.width.toFloat(), out.height.toFloat()),
+ cropOutline = outline,
+ layoutDirection = LayoutDirection.Ltr,
+ density = density
+ ).asAndroidBitmap()
+ if (masked !== out) out.recycle()
+ return masked
+ }
+
+ private fun background(src: Bitmap, op: BackgroundOp): Bitmap {
+ val w = src.width
+ val h = src.height
+ val mask = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ val mc = Canvas(mask)
+ if (op.autoMask != null) {
+ mc.drawBitmap(op.autoMask, null, Rect(0, 0, w, h), Paint(Paint.FILTER_BITMAP_FLAG).apply { color = android.graphics.Color.BLACK })
+ } else {
+ mc.drawColor(android.graphics.Color.BLACK)
+ }
+ val short = minOf(w, h).toFloat()
+ for (s in op.strokes) {
+ val pts = s.points.map { android.graphics.PointF(it.x * w, it.y * h) }
+ if (pts.isEmpty()) continue
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = (s.width * short).coerceAtLeast(1f)
+ strokeCap = Paint.Cap.ROUND
+ strokeJoin = Paint.Join.ROUND
+ if (s.restore) color = android.graphics.Color.BLACK
+ else xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
+ }
+ mc.drawPath(ShapePaths.smooth(pts, false), paint)
+ }
+ val out = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ val oc = Canvas(out)
+ oc.drawBitmap(src, 0f, 0f, null)
+ oc.drawBitmap(mask, 0f, 0f, Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN) })
+ mask.recycle()
+ return out
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/FilterPresets.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/FilterPresets.kt
new file mode 100644
index 0000000..5e62949
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/FilterPresets.kt
@@ -0,0 +1,136 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.ColorMatrix
+import android.graphics.Paint
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageCrosshatchFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageEmbossFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilterGroup
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageHalftoneFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageKuwaharaFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImagePosterizeFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageSketchFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageToonFilter
+import jp.co.cyberagent.android.gpuimage.filter.GPUImageVignetteFilter
+import android.graphics.PointF
+
+/**
+ * One-tap looks. Most are colour matrices (cheap, CPU); the artistic ones run through GPUImage.
+ * [intensity] blends the look with its input: matrices are interpolated towards identity, GPU
+ * looks are alpha-composited over the input.
+ */
+enum class FilterPreset(val label: String) {
+ Vivid("Vivid"),
+ Warm("Warm"),
+ Cool("Cool"),
+ Fade("Fade"),
+ Mono("Mono"),
+ Noir("Noir"),
+ Sepia("Sepia"),
+ Vintage("Vintage"),
+ Chrome("Chrome"),
+ Dramatic("Dramatic"),
+ Golden("Golden"),
+ Teal("Teal & Orange"),
+ Polaroid("Polaroid"),
+ Lomo("Lomo"),
+ Invert("Invert"),
+ Posterize("Posterize"),
+ Sketch("Sketch"),
+ Toon("Toon"),
+ Emboss("Emboss"),
+ Crosshatch("Crosshatch"),
+ Halftone("Halftone"),
+ OilPaint("Oil paint");
+
+ fun matrix(): ColorMatrix? = when (this) {
+ Vivid -> ColorMatrix().apply { setSaturation(1.45f) }.then(contrast(1.08f))
+ Warm -> m(1.10f, 0f, 0f, 0f, 14f, 0f, 1.02f, 0f, 0f, 6f, 0f, 0f, 0.88f, 0f, -4f)
+ Cool -> m(0.92f, 0f, 0f, 0f, -4f, 0f, 1.0f, 0f, 0f, 2f, 0f, 0f, 1.12f, 0f, 14f)
+ Fade -> contrast(0.78f).then(ColorMatrix().apply { setSaturation(0.8f) }).then(offset(18f))
+ Mono -> ColorMatrix().apply { setSaturation(0f) }
+ Noir -> ColorMatrix().apply { setSaturation(0f) }.then(contrast(1.45f))
+ Sepia -> ColorMatrix().apply { setSaturation(0f) }
+ .then(m(1.07f, 0f, 0f, 0f, 38f, 0f, 0.95f, 0f, 0f, 18f, 0f, 0f, 0.78f, 0f, -6f))
+ Vintage -> m(0.9f, 0.1f, 0.05f, 0f, 20f, 0.05f, 0.85f, 0.05f, 0f, 14f, 0.05f, 0.1f, 0.7f, 0f, 10f)
+ .then(contrast(0.9f))
+ Chrome -> contrast(1.2f).then(ColorMatrix().apply { setSaturation(1.15f) })
+ .then(m(1f, 0f, 0f, 0f, -6f, 0f, 1.02f, 0f, 0f, 0f, 0f, 0f, 1.06f, 0f, 6f))
+ Dramatic -> contrast(1.35f).then(ColorMatrix().apply { setSaturation(0.75f) }).then(offset(-10f))
+ Golden -> m(1.12f, 0.05f, 0f, 0f, 16f, 0.02f, 1.05f, 0f, 0f, 10f, 0f, 0f, 0.8f, 0f, -10f)
+ .then(ColorMatrix().apply { setSaturation(1.15f) })
+ Teal -> m(1.1f, 0f, 0f, 0f, 8f, 0f, 1.0f, 0.05f, 0f, 0f, 0f, 0.12f, 1.05f, 0f, 10f)
+ .then(contrast(1.12f))
+ Polaroid -> m(1.438f, -0.062f, -0.062f, 0f, 0f, -0.122f, 1.378f, -0.122f, 0f, 0f, -0.016f, -0.016f, 1.483f, 0f, 0f)
+ .then(offset(-6f)).then(ColorMatrix().apply { setSaturation(0.9f) })
+ Lomo -> ColorMatrix().apply { setSaturation(1.3f) }.then(contrast(1.25f))
+ Invert -> m(-1f, 0f, 0f, 0f, 255f, 0f, -1f, 0f, 0f, 255f, 0f, 0f, -1f, 0f, 255f)
+ else -> null
+ }
+
+ fun gpu(): GPUImageFilter? = when (this) {
+ Lomo -> GPUImageVignetteFilter(PointF(0.5f, 0.5f), floatArrayOf(0f, 0f, 0f), 0.35f, 0.85f)
+ Posterize -> GPUImagePosterizeFilter(6)
+ Sketch -> GPUImageSketchFilter()
+ Toon -> GPUImageToonFilter(0.2f, 10f)
+ Emboss -> GPUImageEmbossFilter(1.5f)
+ Crosshatch -> GPUImageCrosshatchFilter(0.02f, 0.003f)
+ Halftone -> GPUImageHalftoneFilter(0.012f)
+ OilPaint -> GPUImageKuwaharaFilter(4)
+ else -> null
+ }
+
+ companion object {
+ fun apply(context: Context, src: Bitmap, preset: FilterPreset, intensity: Float): Bitmap {
+ val k = intensity.coerceIn(0f, 1f)
+ var cur = src
+ preset.matrix()?.let { cur = AdjustRenderer.applyMatrix(cur, lerp(it, k)) }
+ preset.gpu()?.let { f ->
+ val filtered = GpuRunner.apply(context, cur, f) ?: return cur
+ val blended = if (k >= 0.999f) filtered else blend(cur, filtered, k).also { filtered.recycle() }
+ if (cur !== src) cur.recycle()
+ cur = blended
+ }
+ return if (cur === src) src.copy(Bitmap.Config.ARGB_8888, true) else cur
+ }
+
+ /** Draws [top] over [bottom] with [alpha]; returns a new bitmap. */
+ fun blend(bottom: Bitmap, top: Bitmap, alpha: Float): Bitmap {
+ val out = bottom.copy(Bitmap.Config.ARGB_8888, true)
+ Canvas(out).drawBitmap(
+ top, null, android.graphics.Rect(0, 0, out.width, out.height),
+ Paint(Paint.FILTER_BITMAP_FLAG).apply { this.alpha = (alpha * 255).toInt() }
+ )
+ return out
+ }
+
+ private fun lerp(target: ColorMatrix, k: Float): ColorMatrix {
+ if (k >= 0.999f) return target
+ val id = ColorMatrix().array
+ val t = target.array
+ return ColorMatrix(FloatArray(20) { i -> id[i] + (t[i] - id[i]) * k })
+ }
+ }
+}
+
+private fun m(vararg rgb: Float): ColorMatrix {
+ // 15 values (3 rows) → append identity alpha row.
+ return ColorMatrix(rgb + floatArrayOf(0f, 0f, 0f, 1f, 0f))
+}
+
+private fun contrast(k: Float): ColorMatrix {
+ val t = (1f - k) * 127.5f
+ return ColorMatrix(floatArrayOf(k, 0f, 0f, 0f, t, 0f, k, 0f, 0f, t, 0f, 0f, k, 0f, t, 0f, 0f, 0f, 1f, 0f))
+}
+
+private fun offset(t: Float) =
+ ColorMatrix(floatArrayOf(1f, 0f, 0f, 0f, t, 0f, 1f, 0f, 0f, t, 0f, 0f, 1f, 0f, t, 0f, 0f, 0f, 1f, 0f))
+
+/** Returns this followed by [next] (mutates and returns this). */
+private fun ColorMatrix.then(next: ColorMatrix): ColorMatrix = apply { postConcat(next) }
+
+@Suppress("unused")
+private fun group(vararg f: GPUImageFilter) = GPUImageFilterGroup(f.toList())
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/ImageIo.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/ImageIo.kt
new file mode 100644
index 0000000..306285c
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/ImageIo.kt
@@ -0,0 +1,212 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.content.ContentValues
+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.os.Environment
+import android.provider.MediaStore
+import android.provider.OpenableColumns
+import androidx.exifinterface.media.ExifInterface
+import java.io.File
+import kotlin.math.max
+
+enum class ExportFormat(val label: String, val mime: String, val ext: String) {
+ Jpeg("JPEG", "image/jpeg", "jpg"),
+ Png("PNG", "image/png", "png"),
+ Webp("WEBP", "image/webp", "webp");
+
+ @Suppress("DEPRECATION")
+ val compress: Bitmap.CompressFormat
+ get() = when (this) {
+ Jpeg -> Bitmap.CompressFormat.JPEG
+ Png -> Bitmap.CompressFormat.PNG
+ Webp -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) Bitmap.CompressFormat.WEBP_LOSSY else Bitmap.CompressFormat.WEBP
+ }
+}
+
+enum class MetadataMode { Keep, RemoveLocation, RemoveAll }
+
+data class ExportSettings(
+ val format: ExportFormat = ExportFormat.Jpeg,
+ val quality: Int = 92,
+ val metadata: MetadataMode = MetadataMode.RemoveLocation
+)
+
+object ImageIo {
+
+ data class Bounds(val width: Int, val height: Int)
+
+ /** Pixel size after EXIF orientation is applied. */
+ fun bounds(context: Context, uri: Uri): Bounds? {
+ val o = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, o) }
+ if (o.outWidth <= 0 || o.outHeight <= 0) return null
+ val rot = orientationDegrees(context, uri)
+ return if (rot % 180 != 0) Bounds(o.outHeight, o.outWidth) else Bounds(o.outWidth, o.outHeight)
+ }
+
+ /**
+ * Decodes [uri] so its long edge is at most [maxDim] and its pixel count fits [maxPixels],
+ * with EXIF orientation baked in.
+ */
+ fun decode(context: Context, uri: Uri, maxDim: Int, maxPixels: Long = Long.MAX_VALUE): Bitmap? {
+ val o = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, o) }
+ val w = o.outWidth
+ val h = o.outHeight
+ if (w <= 0 || h <= 0) return null
+ var sample = 1
+ while (max(w, h) / sample > maxDim * 2 || (w.toLong() / sample) * (h.toLong() / sample) > maxPixels * 4) sample *= 2
+ val opts = BitmapFactory.Options().apply {
+ inSampleSize = sample
+ inPreferredConfig = Bitmap.Config.ARGB_8888
+ inMutable = false
+ }
+ var bmp = context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, opts) } ?: return null
+ // Exact downscale to the budget.
+ val scale = minOf(1f, maxDim.toFloat() / max(bmp.width, bmp.height),
+ kotlin.math.sqrt(maxPixels.toDouble() / (bmp.width.toLong() * bmp.height)).toFloat())
+ val m = Matrix()
+ if (scale < 0.999f) m.postScale(scale, scale)
+ applyOrientation(m, exifOrientation(context, uri))
+ if (!m.isIdentity) {
+ val t = Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, m, true)
+ if (t !== bmp) bmp.recycle()
+ bmp = t
+ }
+ return if (bmp.config != Bitmap.Config.ARGB_8888) bmp.copy(Bitmap.Config.ARGB_8888, false).also { bmp.recycle() } else bmp
+ }
+
+ private fun exifOrientation(context: Context, uri: Uri): Int = runCatching {
+ context.contentResolver.openInputStream(uri)?.use {
+ ExifInterface(it).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
+ } ?: ExifInterface.ORIENTATION_NORMAL
+ }.getOrDefault(ExifInterface.ORIENTATION_NORMAL)
+
+ private fun orientationDegrees(context: Context, uri: Uri): Int = when (exifOrientation(context, uri)) {
+ ExifInterface.ORIENTATION_ROTATE_90, ExifInterface.ORIENTATION_TRANSPOSE -> 90
+ ExifInterface.ORIENTATION_ROTATE_180 -> 180
+ ExifInterface.ORIENTATION_ROTATE_270, ExifInterface.ORIENTATION_TRANSVERSE -> 270
+ else -> 0
+ }
+
+ private fun applyOrientation(m: Matrix, orientation: Int) {
+ when (orientation) {
+ ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> m.postScale(-1f, 1f)
+ ExifInterface.ORIENTATION_ROTATE_180 -> m.postRotate(180f)
+ ExifInterface.ORIENTATION_FLIP_VERTICAL -> m.postScale(1f, -1f)
+ ExifInterface.ORIENTATION_TRANSPOSE -> { m.postRotate(90f); m.postScale(-1f, 1f) }
+ ExifInterface.ORIENTATION_ROTATE_90 -> m.postRotate(90f)
+ ExifInterface.ORIENTATION_TRANSVERSE -> { m.postRotate(-90f); m.postScale(-1f, 1f) }
+ ExifInterface.ORIENTATION_ROTATE_270 -> m.postRotate(270f)
+ }
+ }
+
+ fun displayName(context: Context, uri: Uri): String =
+ runCatching {
+ context.contentResolver.query(uri, null, null, null, null)?.use { c ->
+ val i = c.getColumnIndex(OpenableColumns.DISPLAY_NAME)
+ if (i != -1 && c.moveToFirst()) c.getString(i) else null
+ }
+ }.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/') ?: "Image"
+
+ // ── EXIF ────────────────────────────────────────────────────────────────────────────────
+
+ private val ViewTags = listOf(
+ "Camera make" to ExifInterface.TAG_MAKE,
+ "Camera model" to ExifInterface.TAG_MODEL,
+ "Date taken" to ExifInterface.TAG_DATETIME_ORIGINAL,
+ "Lens" to ExifInterface.TAG_LENS_MODEL,
+ "Focal length" to ExifInterface.TAG_FOCAL_LENGTH,
+ "Aperture" to ExifInterface.TAG_F_NUMBER,
+ "Exposure time" to ExifInterface.TAG_EXPOSURE_TIME,
+ "ISO" to ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY,
+ "Flash" to ExifInterface.TAG_FLASH,
+ "White balance" to ExifInterface.TAG_WHITE_BALANCE,
+ "Software" to ExifInterface.TAG_SOFTWARE,
+ "Artist" to ExifInterface.TAG_ARTIST,
+ "Copyright" to ExifInterface.TAG_COPYRIGHT,
+ "Description" to ExifInterface.TAG_IMAGE_DESCRIPTION,
+ )
+
+ /** Tags carried over on export (orientation is reset because edits bake it in). */
+ private val CopyTags = ViewTags.map { it.second } + listOf(
+ ExifInterface.TAG_DATETIME, ExifInterface.TAG_DATETIME_DIGITIZED,
+ ExifInterface.TAG_OFFSET_TIME, ExifInterface.TAG_OFFSET_TIME_ORIGINAL,
+ ExifInterface.TAG_EXPOSURE_BIAS_VALUE, ExifInterface.TAG_METERING_MODE,
+ ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM, ExifInterface.TAG_LENS_MAKE,
+ )
+
+ private val GpsTags = listOf(
+ ExifInterface.TAG_GPS_LATITUDE, ExifInterface.TAG_GPS_LATITUDE_REF,
+ ExifInterface.TAG_GPS_LONGITUDE, ExifInterface.TAG_GPS_LONGITUDE_REF,
+ ExifInterface.TAG_GPS_ALTITUDE, ExifInterface.TAG_GPS_ALTITUDE_REF,
+ ExifInterface.TAG_GPS_TIMESTAMP, ExifInterface.TAG_GPS_DATESTAMP,
+ ExifInterface.TAG_GPS_PROCESSING_METHOD,
+ )
+
+ data class ExifEntry(val label: String, val value: String)
+
+ fun readExif(context: Context, uri: Uri): List<ExifEntry> = runCatching {
+ context.contentResolver.openInputStream(uri)?.use { input ->
+ val exif = ExifInterface(input)
+ val list = ViewTags.mapNotNull { (label, tag) ->
+ exif.getAttribute(tag)?.takeIf { it.isNotBlank() }?.let { ExifEntry(label, it) }
+ }.toMutableList()
+ exif.latLong?.let { (lat, lon) -> list += ExifEntry("Location", "%.5f, %.5f".format(lat, lon)) }
+ list
+ } ?: emptyList()
+ }.getOrDefault(emptyList())
+
+ private fun copyExif(context: Context, source: Uri, target: File, mode: MetadataMode) {
+ if (mode == MetadataMode.RemoveAll) return
+ runCatching {
+ val src = context.contentResolver.openInputStream(source)?.use { ExifInterface(it) } ?: return
+ val dst = ExifInterface(target.absolutePath)
+ val tags = if (mode == MetadataMode.Keep) CopyTags + GpsTags else CopyTags
+ tags.forEach { tag -> src.getAttribute(tag)?.let { dst.setAttribute(tag, it) } }
+ dst.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL.toString())
+ dst.setAttribute(ExifInterface.TAG_SOFTWARE, "ClearPDF")
+ dst.saveAttributes()
+ }
+ }
+
+ // ── Saving ──────────────────────────────────────────────────────────────────────────────
+
+ /** Encodes to a cache file (with EXIF policy applied). */
+ fun encodeToCache(context: Context, bmp: Bitmap, baseName: String, settings: ExportSettings, source: Uri?): File {
+ val dir = File(context.cacheDir, "edited_images").apply { mkdirs() }
+ val safe = baseName.substringBeforeLast('.').ifBlank { "image" }.replace(Regex("[^A-Za-z0-9._ -]"), "_")
+ val file = File(dir, "${safe}_edited_${System.currentTimeMillis()}.${settings.format.ext}")
+ file.outputStream().use { bmp.compress(settings.format.compress, settings.quality.coerceIn(1, 100), it) }
+ // androidx ExifInterface can write JPEG, PNG and WebP containers.
+ if (source != null) copyExif(context, source, file, settings.metadata)
+ return file
+ }
+
+ /** Copies an encoded file into Pictures/ClearPDF. Returns the new content Uri. */
+ fun publishToGallery(context: Context, file: File, format: ExportFormat): Uri? {
+ val values = ContentValues().apply {
+ put(MediaStore.Images.Media.DISPLAY_NAME, file.name)
+ put(MediaStore.Images.Media.MIME_TYPE, format.mime)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/ClearPDF")
+ }
+ }
+ val collection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
+ MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
+ else MediaStore.Images.Media.EXTERNAL_CONTENT_URI
+ val item = context.contentResolver.insert(collection, values) ?: return null
+ return runCatching {
+ context.contentResolver.openOutputStream(item)?.use { out -> file.inputStream().use { it.copyTo(out) } }
+ item
+ }.getOrElse {
+ context.contentResolver.delete(item, null, null)
+ null
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/OverlayRenderer.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/OverlayRenderer.kt
new file mode 100644
index 0000000..a315d05
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/OverlayRenderer.kt
@@ -0,0 +1,155 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.RectF
+import android.graphics.Typeface
+import kotlin.math.max
+import kotlin.math.min
+
+/**
+ * Text overlays and watermarks. Watermark placement (nine anchors + tiled, alpha, rotation,
+ * padding) follows ImageToolbox's feature/watermarking (Apache-2.0), implemented natively here
+ * instead of through the androidwm library.
+ */
+object OverlayRenderer {
+
+ fun typeface(font: TextFont, bold: Boolean, italic: Boolean): Typeface {
+ val family = when (font) {
+ TextFont.Sans -> Typeface.SANS_SERIF
+ TextFont.Serif -> Typeface.SERIF
+ TextFont.Mono -> Typeface.MONOSPACE
+ TextFont.Condensed -> Typeface.create("sans-serif-condensed", Typeface.NORMAL)
+ TextFont.Cursive -> Typeface.create("cursive", Typeface.NORMAL)
+ }
+ val style = when {
+ bold && italic -> Typeface.BOLD_ITALIC
+ bold -> Typeface.BOLD
+ italic -> Typeface.ITALIC
+ else -> Typeface.NORMAL
+ }
+ return Typeface.create(family, style)
+ }
+
+ fun drawText(base: Bitmap, t: TextLayer): Bitmap {
+ val out = base.copy(Bitmap.Config.ARGB_8888, true)
+ drawTextOn(Canvas(out), out.width, out.height, t)
+ return out
+ }
+
+ /** Also used by the live preview overlay so on-screen and exported text match. */
+ fun drawTextOn(canvas: Canvas, w: Int, h: Int, t: TextLayer) {
+ if (t.text.isBlank()) return
+ val short = min(w, h).toFloat()
+ val size = (t.size * short).coerceAtLeast(4f)
+ val fill = Paint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG).apply {
+ textSize = size
+ typeface = typeface(t.font, t.bold, t.italic)
+ color = t.color
+ alpha = (android.graphics.Color.alpha(t.color) * t.alpha).toInt()
+ textAlign = Paint.Align.CENTER
+ }
+ val lines = t.text.split('\n')
+ val fm = fill.fontMetrics
+ val lineH = fm.descent - fm.ascent
+ val totalH = lineH * lines.size
+ val maxW = lines.maxOf { fill.measureText(it) }
+ val cx = t.center.x * w
+ val cy = t.center.y * h
+ canvas.save()
+ canvas.rotate(t.rotation, cx, cy)
+ if (t.backgroundColor != 0) {
+ val pad = size * 0.3f
+ val r = RectF(cx - maxW / 2 - pad, cy - totalH / 2 - pad * 0.6f, cx + maxW / 2 + pad, cy + totalH / 2 + pad * 0.6f)
+ canvas.drawRoundRect(r, pad, pad, Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = t.backgroundColor
+ alpha = (android.graphics.Color.alpha(t.backgroundColor) * t.alpha).toInt()
+ })
+ }
+ val stroke = if (t.outlineColor != 0) Paint(fill).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = size * t.outlineWidth
+ strokeJoin = Paint.Join.ROUND
+ color = t.outlineColor
+ alpha = (android.graphics.Color.alpha(t.outlineColor) * t.alpha).toInt()
+ } else null
+ var baseline = cy - totalH / 2 - fm.ascent
+ for (line in lines) {
+ stroke?.let { canvas.drawText(line, cx, baseline, it) }
+ canvas.drawText(line, cx, baseline, fill)
+ baseline += lineH
+ }
+ canvas.restore()
+ }
+
+ fun drawWatermark(base: Bitmap, p: WatermarkParams): Bitmap {
+ val out = base.copy(Bitmap.Config.ARGB_8888, true)
+ val w = out.width
+ val h = out.height
+ val short = min(w, h).toFloat()
+ val canvas = Canvas(out)
+ val stamp = stampBitmap(p, short) ?: return out
+ val paint = Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG).apply { alpha = (p.alpha * 255).toInt() }
+ val margin = p.spacing * short
+ if (p.position == WatermarkPosition.Tiled) {
+ val stepX = stamp.width + margin * 2
+ val stepY = stamp.height + margin * 2
+ canvas.save()
+ canvas.rotate(p.rotation, w / 2f, h / 2f)
+ val diag = kotlin.math.hypot(w.toFloat(), h.toFloat())
+ var y = (h - diag) / 2f
+ var row = 0
+ while (y < (h + diag) / 2f) {
+ var x = (w - diag) / 2f + if (row % 2 == 1) stepX / 2f else 0f
+ while (x < (w + diag) / 2f) {
+ canvas.drawBitmap(stamp, x, y, paint)
+ x += stepX
+ }
+ y += stepY
+ row++
+ }
+ canvas.restore()
+ } else {
+ val sw = stamp.width.toFloat()
+ val sh = stamp.height.toFloat()
+ val x = when (p.position) {
+ WatermarkPosition.TopLeft, WatermarkPosition.CenterLeft, WatermarkPosition.BottomLeft -> margin
+ WatermarkPosition.TopRight, WatermarkPosition.CenterRight, WatermarkPosition.BottomRight -> w - sw - margin
+ else -> (w - sw) / 2f
+ }
+ val y = when (p.position) {
+ WatermarkPosition.TopLeft, WatermarkPosition.TopCenter, WatermarkPosition.TopRight -> margin
+ WatermarkPosition.BottomLeft, WatermarkPosition.BottomCenter, WatermarkPosition.BottomRight -> h - sh - margin
+ else -> (h - sh) / 2f
+ }
+ canvas.save()
+ canvas.rotate(p.rotation, x + sw / 2, y + sh / 2)
+ canvas.drawBitmap(stamp, x, y, paint)
+ canvas.restore()
+ }
+ stamp.recycle()
+ return out
+ }
+
+ private fun stampBitmap(p: WatermarkParams, short: Float): Bitmap? {
+ p.image?.let { img ->
+ val tw = max(1, (p.size * 4f * short).toInt())
+ val th = max(1, (img.height * tw.toFloat() / img.width).toInt())
+ return Bitmap.createScaledBitmap(img, tw, th, true)
+ }
+ if (p.text.isBlank()) return null
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = (p.size * short).coerceAtLeast(6f)
+ color = p.color
+ typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
+ setShadowLayer(textSize / 14f, 0f, textSize / 24f, 0x66000000)
+ }
+ val fm = paint.fontMetrics
+ val tw = max(1, (paint.measureText(p.text) + paint.textSize * 0.3f).toInt())
+ val th = max(1, (fm.descent - fm.ascent + paint.textSize * 0.2f).toInt())
+ val bmp = Bitmap.createBitmap(tw, th, Bitmap.Config.ARGB_8888)
+ Canvas(bmp).drawText(p.text, paint.textSize * 0.15f, -fm.ascent + paint.textSize * 0.1f, paint)
+ return bmp
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/draw/FloodFill.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/draw/FloodFill.kt
new file mode 100644
index 0000000..8db7055
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/draw/FloodFill.kt
@@ -0,0 +1,225 @@
+/*
+ * ImageToolbox is an image editor for android
+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)
+ * Modified by ClearPDF (2026): repackaged; returns android.graphics.Path for bitmap replay.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * You should have received a copy of the Apache License
+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.
+ */
+
+package com.chethan616.clearpdf.imageeditor.engine.draw
+
+import android.graphics.Bitmap
+import android.graphics.Color
+import android.graphics.Path
+import java.util.LinkedList
+import java.util.Queue
+
+internal class FloodFill(image: Bitmap) {
+ private val path = Path()
+
+ private val width: Int = image.width
+ private val height: Int = image.height
+ private val pixels: IntArray = IntArray(width * height)
+
+ private lateinit var pixelsChecked: BooleanArray
+ private lateinit var ranges: Queue<FloodFillRange>
+ private val filledRanges = mutableListOf<FloodFillRange>()
+
+ private var tolerance = 0
+
+ private var startColorRed = 0
+ private var startColorGreen = 0
+ private var startColorBlue = 0
+ private var startColorAlpha = 0
+
+ init {
+ image.getPixels(pixels, 0, width, 0, 0, width, height)
+ }
+
+ private fun prepare() {
+ // Called before starting flood-fill
+ pixelsChecked = BooleanArray(pixels.size)
+ ranges = LinkedList()
+ filledRanges.clear()
+ }
+
+ // Fills the specified point on the bitmap with the currently selected fill color.
+ // int x, int y: The starting coordinates for the fill
+ fun performFloodFill(
+ x: Int,
+ y: Int,
+ tolerance: Float
+ ): Path? {
+ if (x >= width || y >= height || x < 0 || y < 0) return null
+
+ path.rewind()
+ this.tolerance = Math.round(tolerance * 255).coerceIn(0, 255)
+ // Setup
+ prepare()
+
+ // Get starting color.
+ val startPixel = pixels.getOrNull(width * y + x) ?: return null
+ startColorRed = Color.red(startPixel)
+ startColorGreen = Color.green(startPixel)
+ startColorBlue = Color.blue(startPixel)
+ startColorAlpha = Color.alpha(startPixel)
+
+ // Do first call to flood-fill.
+ linearFill(x, y)
+
+ // Call flood-fill routine while flood-fill ranges still exist on the queue
+ var range: FloodFillRange
+ while (ranges.isNotEmpty()) {
+ // Get Next Range Off the Queue
+ range = ranges.remove()
+
+ // Check Above and Below Each Pixel in the flood-fill Range
+ var downPxIdx = width * (range.Y + 1) + range.startX
+ var upPxIdx = width * (range.Y - 1) + range.startX
+ val upY = range.Y - 1 // so we can pass the y coordinate by ref
+ val downY = range.Y + 1
+ for (i in range.startX..range.endX) {
+ // Start Fill Upwards
+ // if we're not above the top of the bitmap and the pixel above this one is within the color tolerance
+ if (range.Y > 0 && !pixelsChecked[upPxIdx] && isPixelColorWithinTolerance(upPxIdx)) {
+ linearFill(i, upY)
+ }
+
+ // Start Fill Downwards
+ // if we're not below the bottom of the bitmap and the pixel below this one is within the color tolerance
+ if (
+ range.Y < height - 1 && !pixelsChecked[downPxIdx]
+ && isPixelColorWithinTolerance(downPxIdx)
+ ) {
+ linearFill(i, downY)
+ }
+ downPxIdx++
+ upPxIdx++
+ }
+ }
+
+ buildPath()
+
+ return path
+ }
+
+ // Finds the furthermost left and right boundaries of the fill area
+ // on a given y coordinate, starting from a given x coordinate, filling as it goes.
+ // Adds the resulting horizontal range to the queue of flood-fill ranges,
+ // to be processed in the main loop.
+ //
+ // int x, int y: The starting coordinates
+ private fun linearFill(x: Int, y: Int) {
+ // Find Left Edge of Color Area
+ var lFillLoc = x // the location to check/fill on the left
+ var pxIdx = width * y + x
+ while (true) {
+ pixelsChecked[pxIdx] = true
+ lFillLoc--
+ pxIdx--
+ // exit loop if we're at edge of bitmap or color area
+ if (lFillLoc < 0 || pixelsChecked[pxIdx] || !isPixelColorWithinTolerance(pxIdx)) {
+ break
+ }
+ }
+ lFillLoc++
+
+ // Find Right Edge of Color Area
+ var rFillLoc = x // the location to check/fill on the left
+ pxIdx = width * y + x
+ while (true) {
+ pixelsChecked[pxIdx] = true
+ rFillLoc++
+ pxIdx++
+ if (rFillLoc >= width || pixelsChecked[pxIdx] || !isPixelColorWithinTolerance(pxIdx)) {
+ break
+ }
+ }
+ rFillLoc--
+
+ // add range to queue
+ val r = FloodFillRange(lFillLoc, rFillLoc, y)
+ ranges.offer(r)
+ filledRanges.add(r)
+ }
+
+ private fun buildPath() {
+ val sortedRanges = filledRanges.sortedWith(
+ compareBy(
+ { it.startX },
+ { it.endX },
+ { it.Y }
+ )
+ )
+ var current = sortedRanges.firstOrNull() ?: return
+ var endY = current.Y
+
+ sortedRanges.drop(1).forEach { range ->
+ if (
+ range.startX == current.startX &&
+ range.endX == current.endX &&
+ range.Y == endY + 1
+ ) {
+ endY = range.Y
+ } else {
+ path.addRange(current, endY)
+ current = range
+ endY = range.Y
+ }
+ }
+ path.addRange(current, endY)
+ }
+
+ private fun Path.addRange(
+ range: FloodFillRange,
+ endY: Int
+ ) {
+ addRect(
+ range.startX.toFloat(),
+ range.Y.toFloat(),
+ (range.endX + 1).toFloat(),
+ (endY + 1).toFloat(),
+ Path.Direction.CW
+ )
+ }
+
+ // Sees if a pixel is within the color tolerance range.
+ private fun isPixelColorWithinTolerance(px: Int): Boolean {
+ val alpha = pixels[px] ushr 24 and 0xff
+ val red = pixels[px] ushr 16 and 0xff
+ val green = pixels[px] ushr 8 and 0xff
+ val blue = pixels[px] and 0xff
+
+ return alpha >= startColorAlpha - tolerance && alpha <= startColorAlpha + tolerance &&
+ red >= startColorRed - tolerance && red <= startColorRed + tolerance &&
+ green >= startColorGreen - tolerance && green <= startColorGreen + tolerance &&
+ blue >= startColorBlue - tolerance && blue <= startColorBlue + tolerance
+ }
+
+ // Represents a linear range to be filled and branched from.
+ private data class FloodFillRange(
+ val startX: Int,
+ val endX: Int,
+ val Y: Int
+ )
+}
+
+/** Returns the region connected to ([x],[y]) whose colour is within [tolerance] (0..1). */
+fun Bitmap.floodFillPath(x: Int, y: Int, tolerance: Float): Path? = runCatching {
+ val src = if (config == Bitmap.Config.ARGB_8888) this else copy(Bitmap.Config.ARGB_8888, false)
+ FloodFill(src).performFloodFill(
+ x = x.coerceIn(0, width - 1),
+ y = y.coerceIn(0, height - 1),
+ tolerance = tolerance
+ )
+}.getOrNull()
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/draw/ShapePaths.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/draw/ShapePaths.kt
new file mode 100644
index 0000000..58a4831
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/draw/ShapePaths.kt
@@ -0,0 +1,206 @@
+/*
+ * ImageToolbox is an image editor for android
+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)
+ * Modified by ClearPDF (2026): shape/arrow geometry extracted from
+ * feature/draw/presentation/components/utils/PathHelper.kt, rewritten against
+ * android.graphics.Path so the same code serves the live preview and full-resolution replay.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * You should have received a copy of the Apache License
+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.
+ */
+
+package com.chethan616.clearpdf.imageeditor.engine.draw
+
+import android.graphics.Path
+import android.graphics.PathMeasure
+import android.graphics.PointF
+import android.graphics.RectF
+import com.chethan616.clearpdf.imageeditor.engine.ShapeKind
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.sin
+import kotlin.math.sqrt
+import kotlin.random.Random
+
+object ShapePaths {
+
+ /**
+ * Builds the path for [shape] from pixel-space [points]. Freehand shapes use every point;
+ * geometric shapes use the first (down) and last (current) point as the bounding box.
+ */
+ fun build(
+ shape: ShapeKind,
+ points: List<PointF>,
+ strokeWidthPx: Float,
+ polygonVertices: Int = 5,
+ seed: Int = 0
+ ): Path {
+ if (points.isEmpty()) return Path()
+ val down = points.first()
+ val cur = points.last()
+ return when (shape) {
+ ShapeKind.Free, ShapeKind.Lasso -> smooth(points, close = shape == ShapeKind.Lasso)
+ ShapeKind.Arrow -> smooth(points, false).also { endArrow(it, strokeWidthPx) }
+ ShapeKind.DoubleArrow -> smooth(points, false).also {
+ endArrow(it, strokeWidthPx); startArrow(it, strokeWidthPx)
+ }
+ ShapeKind.Line -> line(down, cur)
+ ShapeKind.LineArrow -> line(down, cur).also { endArrow(it, strokeWidthPx) }
+ ShapeKind.DoubleLineArrow -> line(down, cur).also {
+ endArrow(it, strokeWidthPx); startArrow(it, strokeWidthPx)
+ }
+ ShapeKind.Rect, ShapeKind.OutlinedRect -> Path().apply {
+ addRect(box(down, cur), Path.Direction.CW)
+ }
+ ShapeKind.Oval, ShapeKind.OutlinedOval -> Path().apply {
+ addOval(box(down, cur), Path.Direction.CW)
+ }
+ ShapeKind.Triangle, ShapeKind.OutlinedTriangle -> triangle(down, cur)
+ ShapeKind.Polygon, ShapeKind.OutlinedPolygon -> polygon(down, cur, polygonVertices, 0, false)
+ ShapeKind.Star, ShapeKind.OutlinedStar -> star(down, cur, polygonVertices, 0.5f, 0, false)
+ ShapeKind.Spray -> spray(points, strokeWidthPx, seed)
+ ShapeKind.FloodFill -> Path() // resolved against the bitmap by the renderer
+ }
+ }
+
+ private fun box(a: PointF, b: PointF) = RectF(min(a.x, b.x), min(a.y, b.y), max(a.x, b.x), max(a.y, b.y))
+
+ private fun line(a: PointF, b: PointF) = Path().apply { moveTo(a.x, a.y); lineTo(b.x, b.y) }
+
+ /** Quadratic smoothing through the midpoints of consecutive samples. */
+ fun smooth(points: List<PointF>, close: Boolean): Path = Path().apply {
+ val first = points.first()
+ moveTo(first.x, first.y)
+ if (points.size == 1) {
+ lineTo(first.x + 0.01f, first.y + 0.01f)
+ return@apply
+ }
+ for (i in 1 until points.size) {
+ val p0 = points[i - 1]
+ val p1 = points[i]
+ quadTo(p0.x, p0.y, (p0.x + p1.x) / 2f, (p0.y + p1.y) / 2f)
+ }
+ val last = points.last()
+ lineTo(last.x, last.y)
+ if (close) close()
+ }
+
+ private fun triangle(down: PointF, cur: PointF) = Path().apply {
+ moveTo(down.x, down.y)
+ lineTo(cur.x, down.y)
+ lineTo((down.x + cur.x) / 2, cur.y)
+ lineTo(down.x, down.y)
+ close()
+ }
+
+ private fun polygon(down: PointF, cur: PointF, vertices: Int, rotationDegrees: Int, isRegular: Boolean): Path {
+ val left = min(down.x, cur.x); val right = max(down.x, cur.x)
+ val top = min(down.y, cur.y); val bottom = max(down.y, cur.y)
+ val width = right - left; val height = bottom - top
+ val cx = (left + right) / 2f; val cy = (top + bottom) / 2f
+ return Path().apply {
+ if (isRegular) {
+ val radius = min(width, height) / 2f
+ val step = 360f / vertices
+ val start = rotationDegrees - 270.0
+ for (i in 0 until vertices) {
+ val a = Math.toRadians(start + i * step)
+ val x = cx + radius * cos(a).toFloat(); val y = cy + radius * sin(a).toFloat()
+ if (i == 0) moveTo(x, y) else lineTo(x, y)
+ }
+ } else {
+ for (i in 0 until vertices) {
+ val a = Math.toRadians(i * (360.0 / vertices) + rotationDegrees - 270.0)
+ val x = cx + width / 2f * cos(a).toFloat(); val y = cy + height / 2f * sin(a).toFloat()
+ if (i == 0) moveTo(x, y) else lineTo(x, y)
+ }
+ }
+ close()
+ }
+ }
+
+ private fun star(down: PointF, cur: PointF, vertices: Int, innerRatio: Float, rotationDegrees: Int, isRegular: Boolean): Path {
+ val left = min(down.x, cur.x); val right = max(down.x, cur.x)
+ val top = min(down.y, cur.y); val bottom = max(down.y, cur.y)
+ val width = right - left; val height = bottom - top
+ val cx = (left + right) / 2f; val cy = (top + bottom) / 2f
+ return Path().apply {
+ for (i in 0 until 2 * vertices) {
+ val a = Math.toRadians(i * (360.0 / (2 * vertices)) + rotationDegrees - 270.0)
+ val (rx, ry) = if (isRegular) {
+ val outer = min(width, height) / 2f
+ val r = if (i % 2 == 0) outer else outer * innerRatio
+ r to r
+ } else {
+ (if (i % 2 == 0) width else width * innerRatio) / 2f to
+ (if (i % 2 == 0) height else height * innerRatio) / 2f
+ }
+ val x = cx + rx * cos(a).toFloat(); val y = cy + ry * sin(a).toFloat()
+ if (i == 0) moveTo(x, y) else lineTo(x, y)
+ }
+ close()
+ }
+ }
+
+ /** Deterministic spray: the same seed yields the same dots at any resolution. */
+ private fun spray(points: List<PointF>, radius: Float, seed: Int): Path = Path().apply {
+ val rnd = Random(seed)
+ val dot = max(1f, radius / 18f)
+ points.forEach { p ->
+ repeat(40) {
+ val angle = rnd.nextFloat() * PI_2
+ val r = sqrt(rnd.nextFloat()) * radius
+ val x = p.x + r * cos(angle)
+ val y = p.y + r * sin(angle)
+ addOval(RectF(x, y, x + dot, y + dot), Path.Direction.CW)
+ }
+ }
+ }
+
+ private fun endArrow(path: Path, strokeWidth: Float, sizeScale: Float = 3f, angle: Double = 150.0) {
+ val pm = PathMeasure(path, false)
+ val len = pm.length
+ if (len <= 0f) return
+ val last = FloatArray(2); val pre = FloatArray(2)
+ pm.getPosTan(len, last, null)
+ pm.getPosTan(max(0f, len - strokeWidth * sizeScale), pre, null)
+ addArrowHead(path, last[0], last[1], last[0] - pre[0], last[1] - pre[1], strokeWidth * sizeScale, angle)
+ }
+
+ private fun startArrow(path: Path, strokeWidth: Float, sizeScale: Float = 3f, angle: Double = 150.0) {
+ val pm = PathMeasure(path, false)
+ val len = pm.length
+ if (len <= 0f) return
+ val first = FloatArray(2); val second = FloatArray(2)
+ pm.getPosTan(0f, first, null)
+ pm.getPosTan(minOf(len, strokeWidth * sizeScale), second, null)
+ addArrowHead(path, first[0], first[1], first[0] - second[0], first[1] - second[1], strokeWidth * sizeScale, angle)
+ }
+
+ private fun addArrowHead(path: Path, tipX: Float, tipY: Float, vx0: Float, vy0: Float, size: Float, angle: Double) {
+ val n = sqrt(vx0 * vx0 + vy0 * vy0)
+ if (n < 0.0001f || abs(size) < 0.0001f) return
+ val vx = vx0 / n * size; val vy = vy0 / n * size
+ fun rot(deg: Double): Pair<Float, Float> {
+ val r = Math.toRadians(deg)
+ return (vx * cos(r) - vy * sin(r)).toFloat() to (vx * sin(r) + vy * cos(r)).toFloat()
+ }
+ val (x1, y1) = rot(angle)
+ val (x2, y2) = rot(360 - angle)
+ path.moveTo(tipX, tipY); path.rLineTo(x1, y1)
+ path.moveTo(tipX, tipY); path.rLineTo(x2, y2)
+ }
+
+ private const val PI_2 = (Math.PI * 2).toFloat()
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/draw/StrokeRenderer.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/draw/StrokeRenderer.kt
new file mode 100644
index 0000000..48aa750
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/draw/StrokeRenderer.kt
@@ -0,0 +1,133 @@
+/*
+ * ImageToolbox is an image editor for android
+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)
+ * Modified by ClearPDF (2026): paint set-up for pen / highlighter / neon / eraser and the
+ * path-effect (blur, pixelate) brushes adapted from feature/draw DrawUtils.createDrawPaint and
+ * data/AndroidImageDrawApplier, working on normalised strokes with android.graphics.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * You should have received a copy of the Apache License
+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.
+ */
+
+package com.chethan616.clearpdf.imageeditor.engine.draw
+
+import android.graphics.Bitmap
+import android.graphics.BitmapShader
+import android.graphics.BlurMaskFilter
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.Paint
+import android.graphics.PointF
+import android.graphics.PorterDuff
+import android.graphics.PorterDuffXfermode
+import android.graphics.Shader
+import com.chethan616.clearpdf.imageeditor.engine.BlurUtils
+import com.chethan616.clearpdf.imageeditor.engine.BrushKind
+import com.chethan616.clearpdf.imageeditor.engine.DrawStroke
+import com.chethan616.clearpdf.imageeditor.engine.ShapeKind
+import kotlin.math.min
+
+object StrokeRenderer {
+
+ /**
+ * Renders [strokes] onto a copy of [base]. Strokes go onto a transparent layer first so the
+ * eraser removes drawing only, then the layer is composited over the image.
+ */
+ fun render(base: Bitmap, strokes: List<DrawStroke>): Bitmap {
+ val w = base.width
+ val h = base.height
+ val short = min(w, h).toFloat()
+ val layer = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(layer)
+ var blurred: Bitmap? = null
+ val pixelated = HashMap<Int, Bitmap>()
+ for (s in strokes) {
+ val pts = s.points.map { PointF(it.x * w, it.y * h) }
+ val widthPx = (s.width * short).coerceAtLeast(1f)
+ if (s.shape == ShapeKind.FloodFill && s.brush != BrushKind.Eraser) {
+ val p = pts.firstOrNull() ?: continue
+ // Flood fill samples the image as it currently looks (base + drawing so far).
+ val probe = composite(base, layer)
+ probe.floodFillPath(p.x.toInt(), p.y.toInt(), s.floodTolerance)?.let { path ->
+ canvas.drawPath(path, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = s.color; style = Paint.Style.FILL })
+ }
+ probe.recycle()
+ continue
+ }
+ val path = ShapePaths.build(s.shape, pts, widthPx, s.polygonVertices, s.seed)
+ val paint = paintFor(s, widthPx, short)
+ when (s.brush) {
+ BrushKind.Blur -> {
+ val src = blurred ?: BlurUtils.blur(base, s.effectStrength * short).also { blurred = it }
+ paint.shader = BitmapShader(src, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
+ paint.color = Color.BLACK
+ }
+ BrushKind.Pixelate -> {
+ val block = (s.effectStrength * short).toInt().coerceAtLeast(2)
+ val src = pixelated.getOrPut(block) { BlurUtils.pixelate(base, block.toFloat()) }
+ paint.shader = BitmapShader(src, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
+ paint.color = Color.BLACK
+ }
+ else -> Unit
+ }
+ canvas.drawPath(path, paint)
+ }
+ val out = composite(base, layer)
+ layer.recycle()
+ blurred?.recycle()
+ pixelated.values.forEach { it.recycle() }
+ return out
+ }
+
+ fun paintFor(s: DrawStroke, widthPx: Float, short: Float): Paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG).apply {
+ val filled = s.shape.filled && s.brush != BrushKind.Eraser
+ if (filled) {
+ style = Paint.Style.FILL
+ } else {
+ style = Paint.Style.STROKE
+ strokeWidth = widthPx
+ if (s.brush == BrushKind.Highlighter || s.shape.sharp) {
+ strokeCap = Paint.Cap.SQUARE
+ strokeJoin = Paint.Join.MITER
+ } else {
+ strokeCap = Paint.Cap.ROUND
+ strokeJoin = Paint.Join.ROUND
+ }
+ }
+ color = s.color
+ when (s.brush) {
+ BrushKind.Eraser -> {
+ xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
+ strokeCap = Paint.Cap.ROUND
+ strokeJoin = Paint.Join.ROUND
+ }
+ BrushKind.Highlighter -> {
+ // Highlighter: translucent flat ink regardless of chosen alpha.
+ alpha = min(Color.alpha(s.color), 110)
+ }
+ BrushKind.Neon -> {
+ color = Color.WHITE
+ val glow = (s.softness.coerceAtLeast(0.2f) * widthPx * 2f).coerceAtLeast(2f)
+ setShadowLayer(glow, 0f, 0f, (s.color and 0x00FFFFFF) or (0xCC shl 24))
+ }
+ else -> if (s.softness > 0f) {
+ maskFilter = BlurMaskFilter((s.softness * widthPx).coerceAtLeast(0.5f), BlurMaskFilter.Blur.NORMAL)
+ }
+ }
+ }
+
+ private fun composite(base: Bitmap, layer: Bitmap): Bitmap {
+ val out = base.copy(Bitmap.Config.ARGB_8888, true)
+ Canvas(out).drawBitmap(layer, 0f, 0f, null)
+ return out
+ }
+}