Enol Sim贸n
03/02/2025, 2:41 PMEnol Sim贸n
03/02/2025, 2:41 PMfun UIImage.resizeImage(targetSize: CValue<CGSize>): UIImage? {
val image = this
fun UIImage.resizeImage(
targetSize: CValue<CGSize>,
alpha: Double = 1.0,
): UIImage? {
targetSize.useContents {
UIGraphicsBeginImageContextWithOptions(targetSize, false, 0.0)
image.drawInRect(CGRectMake(0.0, 0.0, this.width, this.height))
this@resizeImage.drawInRect(
rect = CGRectMake(0.0, 0.0, this.width, this.height),
blendMode = CGBlendMode.kCGBlendModeNormal,
alpha = alpha,
)
val resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage
}
}
The black and white function:
@OptIn(ExperimentalForeignApi::class)
fun UIImage.toBlackAndWhite(): UIImage? {
val width = size.useContents { width.toInt() }
val height = size.useContents { height.toInt() }
val colorSpace = CGColorSpaceCreateDeviceGray()
val context =
CGBitmapContextCreate(
data = null,
width = width.toULong(),
height = height.toULong(),
bitsPerComponent = 8u,
bytesPerRow = 0u,
space = colorSpace,
bitmapInfo = CGImageAlphaInfo.kCGImageAlphaPremultipliedLast.value,
) ?: return null
val cgImage = this.CGImage ?: return null
CGContextTranslateCTM(context, 0.0, height.toDouble())
CGContextScaleCTM(context, 1.0, -1.0)
CGContextDrawImage(context, CGRectMake(0.0, 0.0, width.toDouble(), height.toDouble()), cgImage)
val grayCGImage = CGBitmapContextCreateImage(context) ?: return null
return UIImage(grayCGImage)
}
Richard
03/02/2025, 3:20 PMEnol Sim贸n
03/02/2025, 3:21 PMEnol Sim贸n
03/02/2025, 3:24 PM