안드로이드 앱 자바(java) 기본형 카메라

기본형 카메라 예시 코드입니다.



 res/layout/activity_main.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"> <SurfaceView android:id="@+id/surfaceView" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:id="@+id/captureButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" android:text="사진 찍기" /> </RelativeLayout>

MainActivity.java

import android.app.Activity; import android.content.pm.PackageManager; import android.hardware.Camera; import android.os.Bundle; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.IOException; public class MainActivity extends Activity implements SurfaceHolder.Callback { private Camera camera; private SurfaceView surfaceView; private SurfaceHolder surfaceHolder; private Button captureButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); surfaceView = findViewById(R.id.surfaceView); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); captureButton = findViewById(R.id.captureButton); captureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (camera != null) { camera.takePicture(null, null, pictureCallback); } } }); } @Override public void surfaceCreated(SurfaceHolder holder) { try { camera = Camera.open(); camera.setDisplayOrientation(90); camera.setPreviewDisplay(holder); camera.startPreview(); } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { if (camera != null) { camera.stopPreview(); camera.setPreviewCallback(null); camera.startPreview(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { if (camera != null) { camera.stopPreview(); camera.release(); camera = null; } } private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { // 이미지 저장 또는 처리 코드를 여기에 추가하세요. Toast.makeText(getApplicationContext(), "사진을 찍었습니다.", Toast.LENGTH_SHORT).show(); camera.startPreview(); } }; }