diff --git a/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt b/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt index 53a92f3..a1f33e5 100644 --- a/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt +++ b/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt @@ -35,6 +35,7 @@ import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.ReadableType import com.facebook.react.bridge.WritableMap import com.facebook.react.common.ReactConstants +import java.io.BufferedInputStream import java.io.ByteArrayInputStream import java.io.File import java.io.FileInputStream @@ -46,7 +47,6 @@ import kotlin.math.roundToInt import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel -import kotlinx.coroutines.isActive import kotlinx.coroutines.launch object MimeType { @@ -58,27 +58,55 @@ object MimeType { class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { private val moduleCoroutineScope = CoroutineScope(Dispatchers.Default) + /** + * Crops whose promise has not settled yet, so invalidation can reject them. [isInvalidated] + * and the set are only touched under [pendingLock], which is never held while a promise is + * settled. + */ + private val pendingPromises = mutableSetOf() + + private val pendingLock = Any() + + private var isInvalidated = false + init { - cleanTask() + moduleCoroutineScope.launch { cleanTask() } } fun invalidate() { - if (moduleCoroutineScope.isActive) { - moduleCoroutineScope.cancel() - } + val pending = + synchronized(pendingLock) { + isInvalidated = true + pendingPromises.toList().also { pendingPromises.clear() } + } + // Clean up before cancelling: `cleanTask` used to run on the scope cancelled here, so it + // was dispatched onto a dead job and never happened at all. cleanTask() + moduleCoroutineScope.cancel() + // Settle the crops that scope will never get to finish, otherwise their promises would + // hang forever. + for (promise in pending) { + promise.reject(JSApplicationIllegalArgumentException(INVALIDATED_MESSAGE)) + } } /** - * Asynchronous task that cleans up cache dirs (internal and, if available, external) of cropped - * image files. This is run when the module is invalidated (i.e. app is shutting down) and when - * the module is instantiated, to handle the case where the app crashed. + * Cleans up the cache dirs (internal and, if available, external) of cropped image files. This + * is run when the module is invalidated (i.e. app is shutting down) and when the module is + * instantiated, to handle the case where the app crashed. Not dispatched through + * [moduleCoroutineScope], since it has to outlive that scope being cancelled. */ private fun cleanTask() { - moduleCoroutineScope.launch { - cleanDirectory(reactContext.cacheDir) - val externalCacheDir = reactContext.externalCacheDir - externalCacheDir?.let { cleanDirectory(it) } + cleanDirectory(reactContext.cacheDir) + val externalCacheDir = reactContext.externalCacheDir + externalCacheDir?.let { cleanDirectory(it) } + } + + /** Settle [promise] unless invalidation already claimed it. */ + private fun settleOnce(promise: Promise, settle: (Promise) -> Unit) { + val claimed = synchronized(pendingLock) { pendingPromises.remove(promise) } + if (claimed) { + settle(promise) } } @@ -153,6 +181,16 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { Pair(targetSize.getDouble("width").toInt(), targetSize.getDouble("height").toInt()) } else Pair(0, 0) + val accepted = + synchronized(pendingLock) { + if (isInvalidated) false else pendingPromises.add(promise) + } + if (!accepted) { + // `moduleCoroutineScope` is cancelled, so the job below would never start and the + // promise would hang. + promise.reject(JSApplicationIllegalArgumentException(INVALIDATED_MESSAGE)) + return + } moduleCoroutineScope.launch { try { val outOptions = BitmapFactory.Options() @@ -185,9 +223,14 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { if (mimeType == MimeType.JPEG) { copyExif(reactContext, Uri.parse(uri), tempFile) } - promise.resolve(getResultMap(tempFile, cropped, mimeType, includeBase64)) - } catch (e: Exception) { - promise.reject(e) + settleOnce(promise) { + it.resolve(getResultMap(tempFile, cropped, mimeType, includeBase64)) + } + } catch (e: Throwable) { + // Errors (e.g. OutOfMemoryError while decoding) must be turned into a rejection + // too: they don't extend Exception and would otherwise escape the coroutine and + // crash the app, leaving the promise unsettled. + settleOnce(promise) { it.reject(e) } } } } @@ -219,11 +262,13 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { BitmapRegionDecoder.newInstance(it) } else { @Suppress("DEPRECATION") BitmapRegionDecoder.newInstance(it, false) - } ?: throw Error("Could not create bitmap decoder. Uri: $uri") + } ?: throw JSApplicationIllegalArgumentException( + "Could not create bitmap decoder. Uri: $uri" + ) val imageHeight: Int = decoder.height val imageWidth: Int = decoder.width - val orientation = getOrientation(reactContext, Uri.parse(uri)) + val orientation = getOrientation(Uri.parse(uri), headers) val (left, top) = when (orientation) { @@ -242,7 +287,16 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { return@use try { val rect = Rect(left, top, right, bottom) - decoder.decodeRegion(rect, outOptions) + val decoded = decoder.decodeRegion(rect, outOptions) + if (decoded == null || orientation == 0) { + decoded + } else { + // `BitmapRegionDecoder` crops raw, un-rotated pixels, so the crop has to be + // rotated into display orientation. Rotating the pixels rather than leaving + // it to an Exif tag means the output is upright for formats that carry no + // such tag, such as PNG and WebP. + transformBitmap(decoded, Matrix().apply { postRotate(orientation.toFloat()) }) + } } finally { decoder.recycle() } @@ -283,9 +337,11 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { BitmapRegionDecoder.newInstance(it) } else { @Suppress("DEPRECATION") BitmapRegionDecoder.newInstance(it, false) - } ?: throw Error("Could not create bitmap decoder. Uri: $uri") + } ?: throw JSApplicationIllegalArgumentException( + "Could not create bitmap decoder. Uri: $uri" + ) - val orientation = getOrientation(reactContext, Uri.parse(uri)) + val orientation = getOrientation(Uri.parse(uri), headers) val (x, y) = when (orientation) { 90 -> yPos to decoder.height - rectWidth - xPos @@ -325,28 +381,66 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { // Decode the bitmap. We have to open the stream again, like in the example linked // above. // Is there a way to just continue reading from the stream? - outOptions.inSampleSize = getDecodeSampleSize(width, height, targetWidth, targetHeight) - - val cropX = (newX / outOptions.inSampleSize.toFloat()).roundToInt() - val cropY = (newY / outOptions.inSampleSize.toFloat()).roundToInt() - val cropWidth = (newWidth / outOptions.inSampleSize.toFloat()).roundToInt() - val cropHeight = (newHeight / outOptions.inSampleSize.toFloat()).roundToInt() - val cropScale = scale * outOptions.inSampleSize - val scaleMatrix = Matrix().apply { setScale(cropScale, cropScale) } - val filter = true - - val rect = Rect(0, 0, decoder.width, decoder.height) - val bitmap = decoder.decodeRegion(rect, outOptions) - - return Bitmap.createBitmap( - bitmap, - cropX, - cropY, - cropWidth, - cropHeight, - scaleMatrix, - filter - ) + // Decode the crop region, never the whole image: `inSampleSize` is derived from the + // region, so decoding everything else allocates a full-resolution bitmap just to + // throw almost all of it away. + val region = + Rect( + newX.roundToInt(), + newY.roundToInt(), + (newX + newWidth).roundToInt(), + (newY + newHeight).roundToInt() + ) + outOptions.inSampleSize = + getDecodeSampleSize(region.width(), region.height(), targetWidth, targetHeight) + + val bitmap = + try { + decoder.decodeRegion(region, outOptions) + ?: throw IOException("Cannot decode bitmap: $uri") + } finally { + decoder.recycle() + } + + // The decoded region is the crop, only downsampled by whatever factor the decoder + // actually applied: `decodeRegion` ignores `inSampleSize` below API 24. + val cropScale = scale * region.width() / bitmap.width.toFloat() + // Resize and rotate into display orientation in one step, so the written pixels are + // upright regardless of the format (PNG and WebP carry no Exif tag to fall back on). + val scaleMatrix = + Matrix().apply { + setScale(cropScale, cropScale) + if (orientation != 0) { + postRotate(orientation.toFloat(), bitmap.width / 2f, bitmap.height / 2f) + } + } + + return transformBitmap(bitmap, scaleMatrix) + } + } + + /** + * The rotation in degrees the source image has to be rotated clockwise by to be displayed + * upright, or 0 when it carries no such information. Read from the image data itself, so it + * works for remote and `data:` URIs as well as files. + */ + private fun getOrientation(uri: Uri, headers: HashMap?): Int { + val exif = + try { + openBitmapInputStream(uri.toString(), headers) + ?.let { input -> input.use { ExifInterface(BufferedInputStream(it)) } } + } catch (e: IOException) { + // Images without Exif data are not decodable as Exif: treat them as upright + // rather than failing the crop. + null + } ?: return 0 + return when ( + exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) + ) { + ExifInterface.ORIENTATION_ROTATE_90 -> 90 + ExifInterface.ORIENTATION_ROTATE_180 -> 180 + ExifInterface.ORIENTATION_ROTATE_270 -> 270 + else -> 0 } } @@ -422,7 +516,14 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { ContentResolver.SCHEME_ANDROID_RESOURCE ) private const val TEMP_FILE_PREFIX = "ReactNative_cropped_image_" + private const val INVALIDATED_MESSAGE = + "Cannot crop an image after the image editor module was invalidated" + /** + * Copied onto the cropped JPEG. Geolocation tags are deliberately absent: a crop is a new + * picture the user may share on its own, and it should not carry where the original + * happened to be taken. + */ @SuppressLint("InlinedApi") private val EXIF_ATTRIBUTES = arrayOf( @@ -461,38 +562,6 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { ExifInterface.TAG_F_NUMBER, ExifInterface.TAG_GAIN_CONTROL, ExifInterface.TAG_GAMMA, - ExifInterface.TAG_GPS_ALTITUDE, - ExifInterface.TAG_GPS_ALTITUDE_REF, - ExifInterface.TAG_GPS_AREA_INFORMATION, - ExifInterface.TAG_GPS_DATESTAMP, - ExifInterface.TAG_GPS_DOP, - ExifInterface.TAG_GPS_LATITUDE, - ExifInterface.TAG_GPS_LATITUDE_REF, - ExifInterface.TAG_GPS_LONGITUDE, - ExifInterface.TAG_GPS_LONGITUDE_REF, - ExifInterface.TAG_GPS_STATUS, - ExifInterface.TAG_GPS_DEST_BEARING, - ExifInterface.TAG_GPS_DEST_BEARING_REF, - ExifInterface.TAG_GPS_DEST_DISTANCE, - ExifInterface.TAG_GPS_DEST_DISTANCE_REF, - ExifInterface.TAG_GPS_DEST_LATITUDE, - ExifInterface.TAG_GPS_DEST_LATITUDE_REF, - ExifInterface.TAG_GPS_DEST_LONGITUDE, - ExifInterface.TAG_GPS_DEST_LONGITUDE_REF, - ExifInterface.TAG_GPS_DIFFERENTIAL, - ExifInterface.TAG_GPS_IMG_DIRECTION, - ExifInterface.TAG_GPS_IMG_DIRECTION_REF, - ExifInterface.TAG_GPS_MAP_DATUM, - ExifInterface.TAG_GPS_MEASURE_MODE, - ExifInterface.TAG_GPS_PROCESSING_METHOD, - ExifInterface.TAG_GPS_SATELLITES, - ExifInterface.TAG_GPS_SPEED, - ExifInterface.TAG_GPS_SPEED_REF, - ExifInterface.TAG_GPS_STATUS, - ExifInterface.TAG_GPS_TIMESTAMP, - ExifInterface.TAG_GPS_TRACK, - ExifInterface.TAG_GPS_TRACK_REF, - ExifInterface.TAG_GPS_VERSION_ID, ExifInterface.TAG_IMAGE_DESCRIPTION, ExifInterface.TAG_IMAGE_UNIQUE_ID, ExifInterface.TAG_ISO_SPEED, @@ -520,6 +589,20 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { ) // Utils + /** + * Apply `matrix` to `source` and release `source` once the result is independent of it. + * `Bitmap.createBitmap` returns `source` itself when the matrix is an identity, which must + * not be recycled in that case. + */ + private fun transformBitmap(source: Bitmap, matrix: Matrix): Bitmap { + val result = + Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true) + if (result !== source) { + source.recycle() + } + return result + } + private fun getResultMap( resizedImage: File, image: Bitmap, @@ -564,25 +647,6 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { return mimeType } - private fun getOrientation(context: Context, uri: Uri): Int { - val file = getFileFromUri(context, uri) - if (file == null) { - return 0 - } - val exif = ExifInterface(file.absolutePath) - return when ( - exif.getAttributeInt( - ExifInterface.TAG_ORIENTATION, - ExifInterface.ORIENTATION_NORMAL - ) - ) { - ExifInterface.ORIENTATION_ROTATE_90 -> 90 - ExifInterface.ORIENTATION_ROTATE_180 -> 180 - ExifInterface.ORIENTATION_ROTATE_270 -> 270 - else -> 0 - } - } - @Throws(IOException::class) private fun copyExif(context: Context, oldImage: Uri, newFile: File) { val oldFile = getFileFromUri(context, oldImage) @@ -598,6 +662,12 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { newExif.setAttribute(attribute, value) } } + // The crop is already rotated to display orientation, so the source's orientation + // must not be carried over on top of it. + newExif.setAttribute( + ExifInterface.TAG_ORIENTATION, + ExifInterface.ORIENTATION_NORMAL.toString() + ) newExif.saveAttributes() } @@ -664,27 +734,18 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { } /** - * Create a temporary file in the cache directory on either internal or external storage, - * whichever is available and has more free space. + * Create a temporary file in the app's internal cache directory. External storage is only + * a fallback for the rare case where there is no internal cache dir: a crop inherits the + * original's Exif data, and external storage is readable by other apps on API <= 29. * * @param mimeType the MIME type of the file to create (image/ *) */ @Throws(IOException::class) private fun createTempFile(context: Context, mimeType: String?): File { - val externalCacheDir = context.externalCacheDir - val internalCacheDir = context.cacheDir - if (externalCacheDir == null && internalCacheDir == null) { + val cacheDir = context.cacheDir ?: context.externalCacheDir + if (cacheDir == null) { throw IOException("No cache directory available") } - val cacheDir: File? = - if (externalCacheDir == null) { - internalCacheDir - } else if (internalCacheDir == null) { - externalCacheDir - } else { - if (externalCacheDir.freeSpace > internalCacheDir.freeSpace) externalCacheDir - else internalCacheDir - } return File.createTempFile( TEMP_FILE_PREFIX, getFileExtensionForType(mimeType),