Android相机预览教程

时间:2012-06-05 12:01:55

标签: android camera preview

我对我遵循的教程有一个小问题。我想用相机预览制作一个Android应用程序,但直到现在我还没有找到任何一个很好的教程来展示如何做到这一点。这是链接The tutorial 如果我可以使用“相机预制”的“有意图相机”,我不是很舒服吗?我该怎么做。

谢谢:)

3 个答案:

答案 0 :(得分:17)

以下教程将为您提供帮助。

http://www.vogella.com/articles/AndroidCamera/article.html

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html

调用内置相机意图拍照。

public class demo extends Activity {

Button ButtonClick;
int CAMERA_PIC_REQUEST = 1337; 


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ButtonClick =(Button) findViewById(R.id.Camera);
    ButtonClick.setOnClickListener(new OnClickListener (){
        @Override
        public void onClick(View view)
        {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            // request code

            startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if( requestCode == 1337)
    {
    //  data.getExtras()
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");

          Now you have received the bitmap..you can pass that bitmap to other activity
          and play with it in this activity or pass this bitmap to other activity
          and then upload it to server.
    }
    else 
    {
        Toast.makeText(demo.this, "Picture NOt taken", Toast.LENGTH_LONG);
    }
    super.onActivityResult(requestCode, resultCode, data);
}
}

答案 1 :(得分:4)

我目前正致力于a fork项目的CameraPreviewSample。这个例子的好处是github源被标记为使相机预览工作所需的几个步骤。

因此,如果您正在调查运行多个标签(查看自述文件以获取详细信息)可能是个好主意。

另一个很好的资源是来自Google的培训文章。对于相机,Android Training Article about Camera control是最好的。

答案 2 :(得分:2)

不建议直接使用SurfaceViewTextureView,而应使用PreviewView。

CameraX Jetpack库中的PreviewView通过在各种Android设备上提供易于开发的,一致的和稳定的API,使开发人员更容易显示摄像机预览。

在xml

<androidx.camera.view.PreviewView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:scaleType="fitCenter" />

在您的代码中

// Create a preview use case instance
val preview = Preview.Builder().build()

//camera selector
val cameraSelector : CameraSelector = CameraSelector.Builder()
      .requireLensFacing(CameraSelector.LENS_FACING_BACK)
      .build()


// Bind the preview use case and other needed user cases to a lifecycle
val camera = cameraProvider.bindToLifecycle(this as LifecycleOwner, cameraSelector, preview)

// Create a surfaceProvider using the bound camera's cameraInfo
val surfaceProvider = previewView.createSurfaceProvider(camera.cameraInfo)

// Attach the surfaceProvider to the preview use case to start preview
preview.setSurfaceProvider(surfaceProvider)

请参阅完整的文档here