Camera2 教程 4:通过TEXTURE OES方式实现相机预览

青橙相机

GLES11Ext.GL_TEXTURE_EXTERNAL_OES的用处是什么?
上一张实现相机预览的每一帧的输出格式是YUV的(YUV),那么这个扩展纹理的作用就是实现YUV格式到RGB的自动转化,我们就不需要再为此写YUV转RGB的代码了

1. 创建xml和Render

//xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.jdf.camera.ui.CameraV2GLSurfaceView
        android:id="@+id/glsurfaceView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
//Activity
   @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera2_oes);
        //获取SurfaceView
        glSurfaceView = findViewById(R.id.glsurfaceView);
        //封装相机操作
        mCameraLoader = new Camera2OESLoader(this);
        //主要是实例化Render,并绑定
        glSurfaceView.init(mCameraLoader, false, Camera2OESActivity.this);
        findViewById(R.id.saveImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageUtils.saveBitmap = true;
            }
        });
    }

//GlSurfaceView
public class CameraV2GLSurfaceView extends GLSurfaceView {
    public static final String TAG = "Filter_CameraV2GLSurfaceView";
    private JImageRender mCameraV2Renderer;

    public void init(Camera2OESLoader camera, boolean isPreviewStarted, Context context) {
        setEGLContextClientVersion(2);

        mCameraV2Renderer = new JImageRender(new JImageFilter(context));
        mCameraV2Renderer.init(this, camera, isPreviewStarted, context);

        setRenderer(mCameraV2Renderer);
    }

    public CameraV2GLSurfaceView(Context context, AttributeSet attributes) {
        super(context, attributes);
    }
}

2 开启相机

在Activity的onResume中,判断glSurfaceView加载完毕后,获取相机相机传感器方向,并且根据GlSurfaceView大小获取合适的预览大小

//Activity
    @Override
    protected void onResume() {
        super.onResume();
        boolean laidOut = ViewCompat.isLaidOut(glSurfaceView);
        boolean b = !glSurfaceView.isLayoutRequested();
        JLog.d(TAG, "onResume.....laidOut[%b],[%b]",laidOut,b);
        if (laidOut && b) {
            mCameraLoader.onResume(glSurfaceView.getWidth(), glSurfaceView.getHeight());
        } else {
            glSurfaceView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                @Override
                public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
                                           int oldRight, int oldBottom) {
                    JLog.d(TAG, "onResume.....onLayoutChange");
                    glSurfaceView.removeOnLayoutChangeListener(this);
                    mCameraLoader.onResume(glSurfaceView.getWidth(), glSurfaceView.getHeight());
                }
            });
        }
    }

Camera2OESLoader.java

    public void onResume(int width, int height) {
        JLog.d(TAG, "onResume[%d,%d]...", width, height);
        mViewWidth = width;
        mViewHeight = height;
        setUpCamera();
    }


    protected void setUpCamera() {
        try {
            //获取屏幕方向,相机传感器方向,和预览大小
            setUpCameraOutputs();
            if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                JLog.e(TAG, "Dont have CAMERA permission");
                return;
            }
            mCameraManager.openCamera(mCameraId, mCameraDeviceCallback, mCameraHandler);
        } catch (CameraAccessException e) {
            JLog.e(TAG, "Opening camera (ID: " + mCameraId + ") failed.");
            e.printStackTrace();
        }
    }


mCameraHandler是根据Camera2OESLoader中HandlerThread创建的,因为后续我们需要再Render线程中启动预览,为了保证相机打开和启动预览在同一个线程,需要指定同一个Handler

相机启动成功后,我们去Render中创建OES纹理id,SufaceTexture和启动预览

3 启动预览

  • JImageRender.onSurfaceCreated

创建OES 纹理id

   @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        JLog.i(TAG, "onSurfaceCreated......");
        mOESTextureId = Utils.createOESTextureObject();
        mFilterEngine.ifNeedInit();

    }
  • JImageRender.onDrawFrame
    然后在onDrawFrame第一次调用时,完成SurfaceTexture初始化和预览启动
   @Override
    public void onDrawFrame(GL10 gl) {

        Long t1 = System.currentTimeMillis();
        if (mSurfaceTexture != null) {
            mSurfaceTexture.updateTexImage();
            mSurfaceTexture.getTransformMatrix(transformMatrix);
        }

        if (!bIsPreviewStarted) {
            bIsPreviewStarted = initSurfaceTexture();
            bIsPreviewStarted = true;
            return;
        }

        glClearColor(1.0f, 0.0f, 0.0f, 0.0f);

        mFilterEngine.onDraw(transformMatrix,mOESTextureId,glCubeBuffer,glTextureBuffer);

        long t2 = System.currentTimeMillis();
        long t = t2 - t1;
        Log.i(TAG, "onDrawFrame: time: " + t);
    }
  • JImageRender. initSurfaceTexture
  public boolean initSurfaceTexture() {
     
        mSurfaceTexture = new SurfaceTexture(mOESTextureId);
        mCameraLoaer.setPreviewTexture(mSurfaceTexture);
        mCameraLoaer.startPreview();
        return true;
    }
  • Camera2OESLoader.startPreview
 public void startPreview() {
       
        mSurfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        final Surface surface = new Surface(mSurfaceTexture);

        try {

            mCameraDevice.createCaptureSession(Arrays.asList( surface), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    try {
                        CaptureRequest.Builder builder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                        builder.addTarget(surface);
                        mCaptureRequest = builder.build();
                        mCameraCaptureSession = session;
                        mCameraCaptureSession.setRepeatingRequest(mCaptureRequest, null, mCameraHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession session) {

                }
            }, mCameraHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

4 绘制渲染

预览启动后成功后,会更新SurfaceTexture,并更新纹理数据对应的纹理举证,然后将该SurfaceTexture对应的OES纹理ID传递到OPENGL进行绘制

    @Override
    public void onDrawFrame(GL10 gl) {

        Long t1 = System.currentTimeMillis();
        if (mSurfaceTexture != null) {
           //更新SurfaceTexture纹理内容
            mSurfaceTexture.updateTexImage();
            mSurfaceTexture.getTransformMatrix(transformMatrix);
        }

        if (!bIsPreviewStarted) {
            bIsPreviewStarted = initSurfaceTexture();
            bIsPreviewStarted = true;
            return;
        }

        glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
        //使用opengl绘制mOESTextureId对应的纹理内容
        mFilterEngine.onDraw(transformMatrix, mOESTextureId,glCubeBuffer,glTextureBuffer)
  
    }

注意:
updateTexImage()方法只能在包OpenGLES环境的线程里调用,即Renderer接口所独立创建的线程当中。一般在onDrawFrame中调用updateTexImage()将数据绑定给OpenGLES对应的纹理对象

JimageFilter.onDraw

  public void onDraw(float[] transformMatrix, int textureId, FloatBuffer cubeBuffer, FloatBuffer textureBuffer) {
      
        GLES30.glUseProgram(glProgId);
           ....
        if (textureId != OpenGlUtils.NO_TEXTURE) {
            ...
           glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
           ...
           glUniformMatrix4fv(uTextureMatrixLocation, 1, false, transformMatrix, 0);
        }
         ...
        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);

    }

onDraw过程与上一节的相机预览流程一致,主要差别有两点

  1. 绑定和解绑纹理id的类型为GL_TEXTURE_EXTERNAL_OES
  2. 需要额外将从SurfaceTexture中产生的变换矩阵uTextureMatrixLocation传递到着色器中

5 定义OES着色器

因为纹理id使用的是OES格式,着色器中纹理类型也要对应修改,相对于上以上相机预览实现,作色器主要有两个变化

顶点着色器中,需要传递SurfaceTexture产生的变换矩阵对象uTextureMatrix,并根据矩阵值调整纹理坐标位置

attribute vec4 position;
uniform mat4 uTextureMatrix;
attribute vec4 inputTextureCoordinate;
varying vec2 textureCoordinate;
void main()
{
  textureCoordinate = (uTextureMatrix * inputTextureCoordinate).xy;
  gl_Position = position;
}`

片元着色器中,需要声明纹理的类型为samplerExternalOES ,而不是sampler2D; 需要在文件头声明使用了samplerExternalOES,否则加载着色器会报错

#extension GL_OES_EGL_image_external : require
precision mediump float;
uniform samplerExternalOES inputImageTexture;
varying vec2 textureCoordinate;
void main()
{
  gl_FragColor = texture2D(inputImageTexture, textureCoordinate);
}

6 显示效果

预览效果

7 流程总结

相机OES预览.png

主要流程为:

  1. 定义GlSurfaceView和定义OEG纹理类型的着色器

  2. 将GlSurfaceView和Render,设置渲染模式

  3. 在GlSurfaceView加载完毕后,启动相机

  4. 在Render的onSurfaceCreate中,完成OES纹理id创建和初始化Opengl对象

  5. 在相机开启成功的时候,在onDrawFrame中完成预览启动;之所以在onDrawFrame启动,是因为其他阶段,相机不一定启动成功

  6. 预览启动成功后,会在Render的每一帧调用时,更新SurfaceTexture的内容,并更新对应的OES纹理id;将纹理id传递到opengl对象中进行渲染

  7. 渲染成功后,预览数据会显示到屏幕上

8 代码位置

代码具体实现参考 QCCamera中的JCamera2OESFboActivity

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

推荐阅读更多精彩内容