如何在Android摄像头中获取从takePicture调用返回的图像数据字节数组?

时间:2012-04-24 06:18:29

标签: java android android-camera

我有一个Android相机应用程序的简单拍照类:

public class SimplePicture implements Picturable, PictureCallback{

    Camera camera;
    byte[] imgData; // image data in bytes


    /**
     *@param c, the camera instance that the Android phone is using.
     */
    public SimplePicture(Camera c){
        this.camera = c;

    }   

    public byte[] getPicture(int exposureCompensation) {
        // TODO Auto-generated method stub
        Parameters p = camera.getParameters();
        p.setExposureCompensation(exposureCompensation);



        if(p.getMaxExposureCompensation() > 0){  // if exposure is supported
            camera.takePicture(null, this, this);
        }


        return imgData; 


    }

    public void onPictureTaken(byte[] data, Camera camera) {
        // TODO Auto-generated method stub
        imgData = data; 

    }


}

你可能会看到我试图让我的getPicture()方法返回所拍摄图像的字节。由于回调是唯一允许我访问imageData的函数,我知道在拍照后图像数据准备就绪时将调用回调函数。 onPictureTaken函数是否会与我的getPicture同时运行 函数,以便返回函数(返回imgData)将在正确设置字节数组之前返回?或者执行是否等待onPictureTaken调用,然后返回?

如果是第二种情况,我想我的工作是正确的。如果是第一种情况,有人可以引导我朝着正确的方向前进。有没有更简单的方法来执行此操作,还是需要使用锁定来确保我的函数以正确的顺序执行?

谢谢

1 个答案:

答案 0 :(得分:1)

无需在onPictureTaken()之外添加新方法。在捕获后的图像中,您将从onPictureTaken()方法获取byte [],这是您将获得Image的byte []的位置。所以你可以将byte []转换为Bitmap。您还可以使用以下代码段获取捕获图像的byte []

private PictureCallback mPicture = new PictureCallback() {

    @Override
    public void onPictureTaken(final byte[] data, Camera camera) {
        createBitmap(data); // Some stuffs to convert byte[] to Bitmap
    }
};