簡體   English   中英

按下按鈕后拍照並保存圖片

[英]Take picture and Save picture after button is pressed

在創建可以捕獲圖片的方法以及如果按下按鈕時可以保存圖片的方法方面需要幫助。

目前,該應用程序啟動后,相機便立即顯示在TextureView中,而我正努力尋找一種捕獲和保存圖片的方法。

它是從屏幕上捕獲還是從實際的電話攝像頭捕獲都沒有關系。

GitHub: https : //github.com/Chalikov/group26/tree/experimental

謝謝。

public class MainActivity extends AppCompatActivity {
    public static final int REQUEST_CAMERA_PERMISSION = 200;
    public static final int CAMERA_REQUEST = 1888;
    private static final String TAG = "AndroidCameraApi";
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    protected CameraDevice cameraDevice;
    protected CameraCaptureSession cameraCaptureSessions;
    protected CaptureRequest.Builder captureRequestBuilder;
    private Button takePictureButton;
    private Button retryButton;
    private Button acceptButton;
    private TextureView textureView;
    private String cameraId;
    private Size imageDimension;


    TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            //open your camera here
            openCamera();
        }
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            // Transform you image captured size according to the surface width and height
        }
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            return false;
        }
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        }
    };
    private ImageReader imageReader;
    private Uri file;
    private boolean mFlashSupported;
    private Handler mBackgroundHandler;
    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            //This is called when the camera is open
            Log.e(TAG, "onOpened");
            cameraDevice = camera;
            createCameraPreview();
        }
        @Override
        public void onDisconnected(CameraDevice camera) {
            cameraDevice.close();
        }
        @Override
        public void onError(CameraDevice camera, int error) {
            cameraDevice.close();
            cameraDevice = null;
        }
    };
    private HandlerThread mBackgroundThread;
    private View view;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        textureView = (TextureView) findViewById(R.id.texture);
        assert textureView != null;
        textureView.setSurfaceTextureListener(textureListener);
        takePictureButton = (Button) findViewById(R.id.btn_takepicture);
        assert takePictureButton != null;
        takePictureButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                takePicture();
                takePictureButton.setVisibility(View.INVISIBLE);


                retryButton = (Button) findViewById(R.id.btn_retry);
                acceptButton = (Button) findViewById(R.id.btn_analyze);
                retryButton.setVisibility(View.VISIBLE);
                acceptButton.setVisibility(View.INVISIBLE);
                retryButton.setOnClickListener(new Button.OnClickListener()
                {
                    public void onClick(View v)
                    {
                        createCameraPreview();
                        retryButton.setVisibility(View.INVISIBLE);
                        acceptButton.setVisibility(View.INVISIBLE);
                        takePictureButton.setVisibility(View.VISIBLE);

                    }
                });
                retryButton.setVisibility(View.VISIBLE); //SHOW the button


                acceptButton.setOnClickListener(new Button.OnClickListener()
                {
                    public void onClick(View v)
                    {
                        createCameraPreview();
                        retryButton.setVisibility(View.INVISIBLE);
                        acceptButton.setVisibility(View.INVISIBLE);
                        takePictureButton.setVisibility(View.VISIBLE);
                    }
                });
                acceptButton.setVisibility(View.VISIBLE); //SHOW the button
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                imageView.setImageURI(file);
            }
        }
    }

    protected void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("Camera Background");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }
    protected void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    protected void takePicture() {

    }

    protected void savePicture() {

    }

//    private static File getOutputMediaFile(){
//        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_PICTURES), "CameraDemo");
//
//        if (!mediaStorageDir.exists()){
//            if (!mediaStorageDir.mkdirs()){
//                return null;
//            }
//        }
//
//        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//        return new File(mediaStorageDir.getPath() + File.separator +
//                "IMG_"+ timeStamp + ".jpg");
//    }

    protected void createCameraPreview() {
        try {
            SurfaceTexture texture = textureView.getSurfaceTexture();
            assert texture != null;
            DisplayMetrics displaymetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            int height = displaymetrics.heightPixels;
            int width = displaymetrics.widthPixels;
            texture.setDefaultBufferSize(height, width);

            Surface surface = new Surface(texture);
            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            captureRequestBuilder.addTarget(surface);
            cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    //The camera is already closed
                    if (null == cameraDevice) {
                        return;
                    }
                    // When the session is ready, we start displaying the preview.
                    cameraCaptureSessions = cameraCaptureSession;
                    updatePreview();
                }
                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
                }
            }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private void openCamera() {
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        Log.e(TAG, "is camera open");
        try {
            cameraId = manager.getCameraIdList()[0];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            assert map != null;
            imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
            // Add permission for camera and let user grant the permission
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
                return;
            }
            manager.openCamera(cameraId, stateCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "openCamera X");
    }
    protected void updatePreview() {
        if(null == cameraDevice) {
            Log.e(TAG, "updatePreview error, return");
        }
        captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        try {
            cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private void closeCamera() {
        if (null != cameraDevice) {
            cameraDevice.close();
            cameraDevice = null;
        }
        if (null != imageReader) {
            imageReader.close();
            imageReader = null;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // close the app
                Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
    @Override
    protected void onResume() {
        takePictureButton.setVisibility(View.VISIBLE);
        super.onResume();
        Log.e(TAG, "onResume");
        startBackgroundThread();
        if (textureView.isAvailable()) {
            openCamera();
        } else {
            textureView.setSurfaceTextureListener(textureListener);
        }
    }
    @Override
    protected void onPause() {
        retryButton.setVisibility(View.INVISIBLE);
        acceptButton.setVisibility(View.INVISIBLE);
        Log.e(TAG, "onPause");
        stopBackgroundThread();
        super.onPause();
        closeCamera();
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.android.project26.MainActivity">

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1">
        <TextureView
            android:id="@+id/texture"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
        <Button
            android:id="@+id/btn_takepicture"
            android:layout_width="79dp"
            android:layout_height="79dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center_horizontal|bottom"
            android:layout_marginBottom="80dp"
            android:background="@drawable/camera_button"
            android:visibility="visible"/>

        <Button
            android:id="@+id/btn_retry"
            android:layout_width="79dp"
            android:layout_height="79dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_gravity="left|bottom"
            android:layout_marginBottom="80dp"
            android:layout_marginLeft="60dp"
            android:background="@drawable/retry"
            android:visibility="invisible" />

        <Button
            android:id="@+id/btn_analyze"
            android:layout_width="79dp"
            android:layout_height="79dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_gravity="right|bottom"
            android:layout_marginBottom="80dp"
            android:layout_marginRight="60dp"
            android:background="@drawable/analyze"
            android:visibility="invisible" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center_vertical|bottom"
            android:background="#4D000000"
            android:orientation="horizontal">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#00ffffff"
                android:text="Gallery"
                android:textColor="#fff"
                android:textSize="12sp"/>

            <Button
                android:id="@+id/camera_menu"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#00ffffff"
                android:text="Camera"
                android:textColor="#fff"
                android:textSize="12sp"/>

        </LinearLayout>

    </FrameLayout>






</LinearLayout>

//根據您的項目修改ID和名稱。 //在onclick監聽器下面需要圖片

Button capture = (Button) findViewById(R.id.btnCapture);
    capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


                        mCamera.takePicture(null, null, mPicture);


           }
    });

//重寫onPictureTaken方法,編寫下面的代碼將其保存到文件中。

 File pictureFile = PATHOFYOURLOCATION;
     FileOutputStream fos = new FileOutputStream(pictureFile);
     fos.write(data);
     Log.d(TAG, "written");
     Toast.makeText(getApplicationContext(), "image saved in "+pictureFile,    Toast.LENGTH_SHORT).show();
     fos.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM