Android camera preview on SurfaceTexture

2019-06-06 08:07发布

问题:

This is my scenario: I am trying to take a picture from the front camera when someone puts in the incorrect password in the lock screen. Basically, I need to be able to take a picture out of the front cam without a preview.

After much googling, I figured out that the way to do it is opengl and SurfaceTexture. You direct the camera preview to a SurfaceTexture, and later extract the picture from this texture somehow. I found this out from the following resources:

  1. https://stackoverflow.com/a/10776349/902572 (suggestion 1)
  2. http://www.freelancer.com/projects/Android-opengl/Android-OpenGL-App-Access-Raw.html, which is the same as (1)
  3. https://groups.google.com/forum/#!topic/android-developers/U5RXFGpAHPE (See Romain's post on 12/22/11)

I understand what is to be done, but i have been unable to correctly put them into code, as I am new to opengl.

回答1:

The CameraToMpegTest example has most of what you need, though it goes well beyond your use case (it's recording a series of preview frames as a video).

The rest of what you need is in ExtractMpegFramesTest. In particular, you want to render to an offscreen pbuffer (rather than a MediaCodec encoder input surface), and you can save the pbuffer contents as a PNG file using saveFrame().

The above are written as small "headless" test cases. You can see similar code in a full app in Grafika.