安卓(Android) 怎么通过相机(Camera)拍摄照片并保存到文件中

2019年10月27日22:05:19安卓(Android) 怎么通过相机(Camera)拍摄照片并保存到文件中已关闭评论 456 1076字阅读3分35秒

1.简介

安卓(Android) 怎么通过相机(Camera)拍摄照片并保存到文件中?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import java.io.File;
import java.io.FileOutputStream;

public class Main {
    private static final File DESTINY_DIR = new File(
            "/sdcard/unlocksecurity/");

    public static void takePicture(final String fileName) {
        Camera camera = null;
        try {
            int camIdx = 1; 
            Camera.getCameraInfo(camIdx, new Camera.CameraInfo());
            camera = Camera.open(camIdx);

            camera.setPreviewTexture(new SurfaceTexture(0));
            camera.startPreview();
            camera.takePicture(null, null, new Camera.PictureCallback() {

                @Override
                public void onPictureTaken(byte[] data, Camera camera) {
                    saveFile(data, fileName);
                    camera.release();
                }
            });
        } catch (Exception e) {
            if (camera != null) {
                camera.release();
            }
        }
    }

    public static void saveFile(byte[] data, String fileName)
            throws RuntimeException {
        if (!DESTINY_DIR.exists() && !DESTINY_DIR.mkdirs()) {
            return;
        }
        File mainPicture = new File(DESTINY_DIR, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(mainPicture);
            fos.write(data);
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException("Image could not be saved.", e);
        }
    }
}

 
继续阅读
编程十万个怎么办