Android cameraX 快速打开相机并预览获取相机流

打开相机并获取相机流,并将yuv数据转换成nv21



1.导入依赖

在app下的build.gradle中加入

 def camerax_version ="1.0.1"

implementation"androidx.camera:camera-core:${camerax_version}"

implementation"androidx.camera:camera-camera2:${camerax_version}"

implementation"androidx.camera:camera-lifecycle:${camerax_version}"

implementation"androidx.camera:camera-view:1.0.0-alpha28"

2.相机布局文件

使用androidx 的布局

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">

    <androidx.camera.view.PreviewView

        android:id="@+id/textureView"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        tools:layout_editor_absoluteX="0dp"

        tools:layout_editor_absoluteY="0dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

3.打开相机

private var textureView:PreviewView? =null

private val executor =Executors.newSingleThreadExecutor()

private val permissionsRequestCode =Random.nextInt(0,10000)

private var lensFacing:Int =CameraSelector.LENS_FACING_FRONT

//打开相机需要的权限

private val permissions =listOf(Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE)

override fun onCreate(savedInstanceState:Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        textureView = findViewById(R.id.textureView);

}

//先检测权限如果有权限就打开相机

override fun onResume() {

        super.onResume()

    if (!hasPermissions(this)) { //检测权限

        ActivityCompat.requestPermissions(

                this,permissions.toTypedArray(),permissionsRequestCode

        )

    }else {

        bindCameraUseCases()//打开相机

    }

}

/** 绑定预览和获取图片数据*/

@SuppressLint("UnsafeExperimentalUsageError","UnsafeOptInUsageError")

private fun bindCameraUseCases() =textureView?.post{

     val cameraProviderFuture =ProcessCameraProvider.getInstance(this)

     cameraProviderFuture.addListener(Runnable {

          val cameraProvider =cameraProviderFuture.get()

          val preview =textureView?.display?.let {

               Preview.Builder()

              .setTargetAspectRatio(AspectRatio.RATIO_4_3)

              .setTargetRotation(it.rotation)

              .build()

     }

     val imageAnalysis =ImageAnalysis.Builder()

           .setTargetAspectRatio(AspectRatio.RATIO_4_3)

           .setTargetRotation(textureView!!.display.rotation)

            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)

            .build()

      var frameCounter =0

      var lastFpsTimestamp =System.currentTimeMillis()

      var yuvBits:ByteBuffer? =null

       imageAnalysis.setAnalyzer(executor,ImageAnalysis.Analyzer{ image->

            val yuvBuffer = image.image?.let { YuvByteBuffer(it,yuvBits)} //获取相机流并转换成nv21

            image.close()

          //检测相机帧率

            val frameCount =10

            if (++frameCounter %frameCount ==0) {

                 frameCounter =0

                val now =System.currentTimeMillis()

                val delta =now -lastFpsTimestamp

                val fps =1000 *frameCount.toFloat() /delta

                Log.d(TAG,"FPS: ${"%.02f".format(fps)}")

                 lastFpsTimestamp =now

            }

       })

// Create a new camera selector each time, enforcing lens facing

   val cameraSelector =CameraSelector.Builder().requireLensFacing(lensFacing).build()

// Apply declared configs to CameraX using the same lifecycle owner

    cameraProvider.unbindAll()

         val camera =cameraProvider.bindToLifecycle(

            this as LifecycleOwner,cameraSelector,preview,imageAnalysis

          )

    val c:CameraInfo =camera.cameraInfo;

// Use the camera object to link our preview use case with the view

   preview?.setSurfaceProvider(textureView?.surfaceProvider)

  },ContextCompat.getMainExecutor(this))

  }


/** Convenience method used to check if all permissions required by this app are granted */

private fun hasPermissions(context:Context) =permissions.all {

    ContextCompat.checkSelfPermission(context,it) ==PackageManager.PERMISSION_GRANTED

}

override fun onRequestPermissionsResult(

requestCode:Int,

permissions:Array,

grantResults:IntArray

) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults)

if (requestCode ==permissionsRequestCode && hasPermissions(this)) {

bindCameraUseCases()

}else {

finish()// If we don't have the required permissions, we can't run

    }

}

4.YUV转nv21工具



@kotlin.annotation.Retention(AnnotationRetention.SOURCE)

@IntDef(ImageFormat.NV21,ImageFormat.YUV_420_888)

annotation class YuvType

class YuvByteBuffer(image:Image, dstBuffer:ByteBuffer? =null) {

@YuvType

    val type:Int

    val buffer:ByteBuffer

    init {

val wrappedImage = ImageWrapper(image)

type =if (wrappedImage.u.pixelStride ==1) {

ImageFormat.YUV_420_888

        }else {

ImageFormat.NV21

        }

val size = image.width * image.height *3 /2

        buffer =if (

dstBuffer ==null ||dstBuffer.capacity()

dstBuffer.isReadOnly || !dstBuffer.isDirect

        ) {

ByteBuffer.allocateDirect(size) }

else {

dstBuffer

}

buffer.rewind()

removePadding(wrappedImage)

}

// Input buffers are always direct as described in

// https://developer.android.com/reference/android/media/Image.Plane#getBuffer()

    private fun removePadding(image:ImageWrapper) {

val sizeLuma = image.y.width * image.y.height

        val sizeChroma = image.u.width * image.u.height

        if (image.y.rowStride > image.y.width) {

removePaddingCompact(image.y,buffer,0)

}else {

buffer.position(0)

buffer.put(image.y.buffer)

}

if (type ==ImageFormat.YUV_420_888) {

if (image.u.rowStride > image.u.width) {

removePaddingCompact(image.u,buffer,sizeLuma)

removePaddingCompact(image.v,buffer,sizeLuma +sizeChroma)

}else {

buffer.position(sizeLuma)

buffer.put(image.u.buffer)

buffer.position(sizeLuma +sizeChroma)

buffer.put(image.v.buffer)

}

}else {

if (image.u.rowStride > image.u.width *2) {

removePaddingNotCompact(image,buffer,sizeLuma)

}else {

buffer.position(sizeLuma)

var uv = image.v.buffer

                val properUVSize = image.v.height * image.v.rowStride -1

                if (uv.capacity() >properUVSize) {

uv = clipBuffer(image.v.buffer,0,properUVSize)

}

buffer.put(uv)

val lastOne = image.u.buffer[image.u.buffer.capacity() -1]

buffer.put(buffer.capacity() -1,lastOne)

}

}

buffer.rewind()

}

private fun removePaddingCompact(

plane:PlaneWrapper,

dst:ByteBuffer,

offset:Int

    ) {

require(plane.pixelStride ==1){

            "use removePaddingCompact with pixelStride == 1"

        }

        val src = plane.buffer

        val rowStride = plane.rowStride

        var row:ByteBuffer

        dst.position(offset)

for (i in 0 until plane.height) {

row = clipBuffer(src,i *rowStride, plane.width)

dst.put(row)

}

}

private fun removePaddingNotCompact(

image:ImageWrapper,

dst:ByteBuffer,

offset:Int

    ) {

require(image.u.pixelStride ==2){

            "use removePaddingNotCompact pixelStride == 2"

        }

        val width = image.u.width

        val height = image.u.height

        val rowStride = image.u.rowStride

        var row:ByteBuffer

        dst.position(offset)

for (i in 0 until height -1) {

row = clipBuffer(image.v.buffer,i *rowStride,width *2)

dst.put(row)

}

row = clipBuffer(image.u.buffer, (height -1) *rowStride -1,width *2)

dst.put(row)

}

private fun clipBuffer(buffer:ByteBuffer, start:Int, size:Int):ByteBuffer {

val duplicate = buffer.duplicate()

duplicate.position(start)

duplicate.limit(start + size)

return duplicate.slice()

}

private class ImageWrapper(image:Image) {

val width= image.width

        val height = image.height

        val y = PlaneWrapper(width,height, image.planes[0])

val u = PlaneWrapper(width /2,height /2, image.planes[1])

val v = PlaneWrapper(width /2,height /2, image.planes[2])

// Check this is a supported image format

// https://developer.android.com/reference/android/graphics/ImageFormat#YUV_420_888

        init {

require(y.pixelStride ==1){

                "Pixel stride for Y plane must be 1 but got ${y.pixelStride}instead."

            }

            require(u.pixelStride ==v.pixelStride &&u.rowStride ==v.rowStride){

                "U and V planes must have the same pixel and row strides " +

"but got pixel=${u.pixelStride} row=${u.rowStride} for U " +

"and pixel=${v.pixelStride} and row=${v.rowStride}for V"

            }

            require(u.pixelStride ==1 ||u.pixelStride ==2){

                "Supported" +" pixel strides for U and V planes are 1 and 2"

            }

        }

}

private class PlaneWrapper(width:Int, height:Int, plane:Image.Plane) {

val width = width

val height = height

val buffer:ByteBuffer = plane.buffer

        val rowStride = plane.rowStride

        val pixelStride = plane.pixelStride

    }

}

5.AndroidManifest.xml

<!-- Declare features -->

<uses-feature android:name="android.hardware.camera" />

<!-- Declare permissions -->

<uses-permission android:name="android.permission.CAMERA" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

下载地址:https://download.csdn.net/download/qq_28884137/31845235

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容