Anant Kumar Gupta
06/04/2025, 5:29 PMCGImage
in Kotlin/Native?
Warning - Cannot access class 'cnames. structs. CGImage' in the expression type. While it may work, this case indicates a configuration mistake and can lead to avoidable compilation errors, so it may be forbidden soon. Check your module classpath for missing or conflicting dependencies.
fun generateVideoThumbnailIOS(
uri: String
): ImageBitmap? = memScoped {
val nsUrl = NSURL.Companion.fileURLWithPath(uri.removePrefix("file://"))
val asset = AVURLAsset.URLAssetWithURL(nsUrl, null)
val generator = AVAssetImageGenerator(asset)
generator.appliesPreferredTrackTransform = true
val requestedTime = CMTimeMake(1, 1).useContents { readValue() }
val actualTime: CMTime = alloc<CMTime>()
val errorPtr = alloc<ObjCObjectVar<NSError?>>()
val cgImage = generator.copyCGImageAtTime(
requestedTime = requestedTime,
actualTime = actualTime.ptr,
error = errorPtr.ptr
) ?: run {
println("Error: ${errorPtr.value?.localizedDescription}")
return@memScoped null
}
val uiImage = UIImage.imageWithCGImage(cgImage)
val nsData = uiImage.pngRepresentation() ?: return@memScoped null
val length = nsData.length.toInt()
val bytePtr = nsData.bytes?.reinterpret<ByteVar>() ?: return@memScoped null
val byteArray = bytePtr.readBytes(length)
val finalThumbnail = Image.makeFromEncoded(byteArray).toComposeImageBitmap()
return@memScoped finalThumbnail
}