@cxm-2016
2016-09-19T15:25:26.000000Z
字数 1842
阅读 2575
android
no
Android应用提供了Camera来控制拍照,其使用步骤如下:
- 1,通过Camera的open()方法打开相机(默认打开后置摄像头,也可以通过指定ID打开相应的摄像头)
- 2,通过Camera的getParameters()方法获取拍照参数对象
- 3,调用Camera的startPreview()方法开始预览取景,在取景前需要调用Camera的setPreviewDisplay(SurfaceHolder)设置显示
- 4,调用Camera的takePicture()方法拍照
- 5,调用Camera的stopPreview()取消预览,并调用release()方法释放资源
<uses-permission android:name="android.permission.CAMERA"/>
注意:android.hardware.Camera已经被废弃,已经有了新的拍照架构camera2,这里的示例仍然是老的版本
class CaptureActivity : BaseActivity<IPresenter>() {
var isPreview = false
val camera: Camera = Camera.open()
val path = "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath}/Camera"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_capture)
camera.setDisplayOrientation(90)
val parameters = camera.parameters
parameters.setPreviewSize(width, height)//预览图片的大小
parameters.setPreviewFpsRange(4, 10)//每秒显示帧数的最小值和最大值
parameters.pictureFormat = ImageFormat.JPEG//保存图片的格式
parameters.set("jpeg-quality", 100)//保存图片的质量
parameters.setPictureSize(width, height)//保存照片的尺寸
cSurfaceView.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
cSurfaceView.holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
}
override fun surfaceDestroyed(holder: SurfaceHolder?) {
if (isPreview) camera.stopPreview()
camera.release()
}
override fun surfaceCreated(holder: SurfaceHolder) {
camera.setPreviewDisplay(holder)
camera.startPreview()
}
})
cCapture.setOnClickListener { capture() }
}
fun capture() {
camera.autoFocus { success, camera ->
if (success) {
camera.takePicture({
//快门瞬间回调
}, { data, camera ->
//图片原始信息回调
}, { data, camera ->
//拍照完成回调
val file = FileUtils(path, DateUtils.getTimeStamp() + ".jpg")
file.clear()
file.append(data)
file.close()
camera.stopPreview()
camera.startPreview()
isPreview = true
})
}
}
}
}