kotlin 使用MediaProjectionManager进行屏幕截图并转换为宽度错误的位图

9gm1akwq  于 2023-04-07  发布在  Kotlin
关注(0)|答案(1)|浏览(254)

我正在制作一个应用程序,可以使用MediaProjectionManager对屏幕进行截图,但我注意到在一些设备上,它会在图像周围添加黑色边距。而不是正常打印屏幕。
有人能帮我吗
这是我的代码:

fun startCapture(resultCode: Int, data: Intent) {
    mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data)
    imageReader = ImageReader.newInstance(
        displayMetrics.widthPixels, displayMetrics.heightPixels,
        android.graphics.PixelFormat.RGBA_8888, 2
    )
    virtualDisplay = mediaProjection?.createVirtualDisplay(
        VIRTUAL_NAME_DISPLAY,
        displayMetrics.widthPixels, displayMetrics.heightPixels,
        displayMetrics.densityDpi, VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY or VIRTUAL_DISPLAY_FLAG_PUBLIC,
        imageReader?.surface, null, null
    )
}

fun captureScreenshot(): Bitmap? {
    val image: Image? = imageReader?.acquireLatestImage()
    val bitmap: Bitmap? = image?.let { imageToBitmap(it) }
    image?.close()
    saveBitmap(bitmap)
    return bitmap
}

private fun imageToBitmap(image: Image): Bitmap? {
    val planes = image.planes
    val buffer = planes[0].buffer
    val pixelStride = planes[0].pixelStride
    val rowStride = planes[0].rowStride
    val rowPadding = rowStride - pixelStride * displayMetrics.widthPixels

    val bitmap = Bitmap.createBitmap(
        displayMetrics.widthPixels + rowPadding / pixelStride,
        displayMetrics.heightPixels, Bitmap.Config.ARGB_8888
    )
    bitmap.copyPixelsFromBuffer(buffer)
    return bitmap
}
wr98u20j

wr98u20j1#

我设法通过添加一个新的createBitmap来解决它。

private fun imageToBitmap(image: Image): Bitmap? {
    val planes = image.planes
    val buffer = planes[0].buffer
    val pixelStride = planes[0].pixelStride
    val rowStride = planes[0].rowStride
    val rowPadding = rowStride - pixelStride * displayMetrics.widthPixels

    val bitmap = Bitmap.createBitmap(
        displayMetrics.widthPixels + rowPadding / pixelStride,
        displayMetrics.heightPixels, Bitmap.Config.ARGB_8888
    )
    bitmap.copyPixelsFromBuffer(buffer)
    return Bitmap.createBitmap(bitmap, 0, 0,
        displayMetrics.widthPixels,
        displayMetrics.heightPixels)
}

相关问题