Android 无预览拍照

废话不多说,直接上代码

1,定义相机类kcamera

package com.kneron.kfaceservice;
 
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.util.Log;
 
import java.util.List;
 
/**
 * Created by lcz on 19-7-25.
 */
 
public class kcamera {
    public kcamera(Camera.PreviewCallback cb){
        mst = new SurfaceTexture(0);
        this.mPreviewCb=cb;
    }
    private Camera.PreviewCallback mPreviewCb;
    private final static String TAG="kcamera";
    /**
     * ASPECT_RATIO_W and ASPECT_RATIO_H define the aspect ratio
     * of the Surface. They are used when {@link #onMeasure(int, int)}
     * is called.
     */
    private final float ASPECT_RATIO_W = 4.0f;
    private final float ASPECT_RATIO_H = 3.0f;
 
    /**
     * The maximum dimension (in pixels) of the preview frames that are produced
     * by the Camera object. Note that this should not be intended as
     * the final, exact, dimension because the device could not support
     * it and a lower value is required (but the aspect ratio should remain the same).<br />
     * See {@link CameraPreview#getBestSize(List, int)} for more information.
     */
    private final int PREVIEW_MAX_WIDTH = 640;
 
    /**
     * The maximum dimension (in pixels) of the images produced when a
     * {@link Camera.PictureCallback#onPictureTaken(byte[], Camera)} event is
     * fired. Again, this is a maximum value and could not be the
     * real one implemented by the device.
     */
    private final int PICTURE_MAX_WIDTH = 640;
    /**
     * 'camera' is the object that references the hardware device
     * installed on your Android phone.
     */
    private Camera camera;
    /**
     * Phone can have multiple cameras, so 'cameraID' is a
     * useful variable to store which one of the camera is active.
     * It starts with value -1
     */
    private int cameraID=-1;
    SurfaceTexture mst;
    /**
     * [IMPORTANT!] The most important method of this Activity: it asks for an instance
     * of the hardware camera(s) and save it to the private field {@link #camera}.
     *
     * @return TRUE if camera is set, FALSE if something bad happens
     */
    public boolean setCameraInstance() {
        if (this.camera != null) {
            // do the job only if the camera is not already set
            Log.i(TAG, "setCameraInstance(): camera is already set, nothing to do");
            return true;
        }
 
 
        // warning here! starting from API 9, we can retrieve one from the multiple
        // hardware cameras (ex. front/back)
 
        if (this.cameraID < 0) {
            // at this point, it's the first time we request for a camera
            Camera.CameraInfo camInfo = new Camera.CameraInfo();
            for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
                Camera.getCameraInfo(i, camInfo);
 
                if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    // in this example we'll request specifically the back camera
                    try {
                        Log.d(TAG, "setCameraInstance(): trying to open camera #" + i);
                        this.camera = Camera.open(i);
                        this.cameraID = i; // assign to cameraID this camera's ID (O RLY?)
                        this.camera.setPreviewCallback(mPreviewCb);
                        camera.setPreviewTexture(mst);
//                      int buffersize = 640 * 480* ImageFormat.getBitsPerPixel(ImageFormat.NV21) / 8;
//                       previewBuffer = new byte[buffersize];
//                       camera.addCallbackBuffer(previewBuffer);
//                       camera.setPreviewCallbackWithBuffer(this);
 
//                      SurfaceTexture mst = new SurfaceTexture(0);
 
                        Camera.Parameters parameters = camera.getParameters();
                        Camera.Size bestPreviewSize = getBestSize(parameters.getSupportedPreviewSizes(), PREVIEW_MAX_WIDTH);
                        //Camera.Size bestPictureSize = getBestSize(parameters.getSupportedPictureSizes(), PICTURE_MAX_WIDTH);
                        parameters.setPreviewSize(bestPreviewSize.width, bestPreviewSize.height);
                        parameters.setPreviewFormat(ImageFormat.NV21); // NV21 is the most supported format for preview frames
                        parameters.setPictureFormat(ImageFormat.JPEG); // JPEG for full resolution images
                        try {
                            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                        }
                        catch (NoSuchMethodError e) {
                            // remember that not all the devices support a given feature
                            Log.e(TAG, "setupCamera(): this camera ignored some unsupported settings.", e);
                        }
                        camera.setParameters(parameters); // save everything
                        camera.startPreview();
                        return true;
                    } catch (Exception e) {
                        // something bad happened! this camera could be locked by other apps
                        Log.e(TAG, "setCameraInstance(): trying to open camera #" + i + " but it's locked", e);
                    }
                }
            }
        }
 
 
//         we could reach this point in two cases:
//         - the API is lower than 9
//         - previous code block failed
//         hence, we try the classic method, that doesn't ask for a particular camera
        if (this.camera == null) {
            try {
                //openCameraBegin=System.currentTimeMillis();
                Log.d(TAG, "setCameraInstance(): trying to open camera");
                this.camera = Camera.open(1);
                this.cameraID = 1;
            } catch (RuntimeException e) {
                // this is REALLY bad, the camera is definitely locked by the system.
 
                Log.e(TAG,
                        "setCameraInstance(): trying to open default camera but it's locked. "
                                + "The camera is not available for this app at the moment.", e
                );
                return false;
            }
        }
 
        // here, the open() went good and the camera is available
        Log.i(TAG, "setCameraInstance(): successfully set camera #" + this.cameraID);
        return true;
    }
 
    /**
     * [IMPORTANT!] Another very important method: it releases all the resources and the locks
     * we created while using the camera. It MUST be called everytime the app exits, crashes,
     * is paused or whatever. The order of the called methods are the following: <br />
     * <p>
     * 1) stop any preview coming to the GUI, if running <br />
     * 2) call {@link Camera#release()} <br />
     * 3) set our camera object to null and invalidate its ID
     */
    public void releaseCameraInstance() {
        if (this.camera != null) {
            try {
                this.camera.stopPreview();
            } catch (Exception e) {
                Log.i(TAG, "releaseCameraInstance(): tried to stop a non-existent preview, this is not an error");
            }
 
            this.camera.setPreviewCallback(null);
            this.camera.release();
            this.camera = null;
            this.cameraID = -1;
            Log.i(TAG, "releaseCameraInstance(): camera has been released.");
        }
    }
    /**
     * [IMPORTANT!] This is a convenient function to determine what's the proper
     * preview/picture size to be assigned to the camera, by looking at
     * the list of supported sizes and the maximum value given
     * @param sizes sizes that are currently supported by the camera hardware,
     * retrived with {@link Camera.Parameters#getSupportedPictureSizes()} or {@link Camera.Parameters#getSupportedPreviewSizes()}
     * @param widthThreshold the maximum value we want to apply
     * @return an optimal size <= widthThreshold
     */
    private Camera.Size getBestSize(List<Camera.Size> sizes, int widthThreshold) {
        Camera.Size bestSize = null;
 
        for (Camera.Size currentSize : sizes) {
            boolean isDesiredRatio = ((currentSize.width / ASPECT_RATIO_W) == (currentSize.height / ASPECT_RATIO_H));
            boolean isBetterSize = (bestSize == null || currentSize.width > bestSize.width);
            boolean isInBounds = currentSize.width <= widthThreshold;
 
            if (isDesiredRatio && isInBounds && isBetterSize) {
                bestSize = currentSize;
            }
        }
 
        if (bestSize == null) {
            bestSize = sizes.get(0);
            Log.e(TAG, "determineBestSize(): can't find a good size. Setting to the very first...");
        }
 
        Log.i(TAG, "determineBestSize(): bestSize is " + bestSize.width + "x" + bestSize.height);
        return bestSize;
    }
}

2 实现 Camera.PreviewCallback,可以写在你的Activity里面

@Override
public void onPreviewFrame(byte[] data, Camera camera) {
}

3 使用

mcamera=new kcamera(this);//一般写在oncreat里面即可
boolean ret= mcamera.setCameraInstance();//开启预览
 
mcamera.releaseCameraInstance();//别忘记关闭
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,451评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,172评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,782评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,709评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,733评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,578评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,320评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,241评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,686评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,878评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,992评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,715评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,336评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,912评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,040评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,173评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,947评论 2 355