Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -325,28 +325,39 @@ 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)
// 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()
}

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
// 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()
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
)
val cropped =
Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, scaleMatrix, filter)
if (cropped !== bitmap) {
bitmap.recycle()
}
return cropped
}
}

Expand Down
Loading