android相机保存文件错误

时间:2012-09-18 16:10:07

标签: android camera

我正在开发一个基于相机功能的Android应用程序。我的程序遇到了一些麻烦,我无法弄清楚。我的mCurrentImagePath在初始化时始终为null。 logcat显示它永远不会命中takepicture()函数,因此永远不会给出值。我试图让线程休眠,以便后面的位图操作可以等到相机保存好图片,但它仍然无法正常工作。但是,如果我不读取我拍摄的图片,应用程序工作得很完美,它可以很好地保存图片。我还尝试使用bitmapfactory.decodebyte()直接操作元数据,但它也失败了。任何人都可以告诉我哪个部分出错了?那会非常有帮助。非常感谢你!!!

private static final String IMAGE_DIRECTORY ="sdcard/DCIM/Camera";
public static String mCurrentImagePath = null;
private CameraView cv;
private Camera mCamera = null;

public Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {

    public void onPictureTaken(byte[] data, Camera camera) {

        try{
            isFinish = false;
            long timeTaken = System.currentTimeMillis();
            mCurrentImagePath = IMAGE_DIRECTORY + "/"+ createName(timeTaken) + ".jpg";
            File file = new File(mCurrentImagePath);
            Log.d("path", "mCurrentImagePath_takepicture = " + mCurrentImagePath);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data);
            fos.flush();
            fos.close();
            Toast.makeText(OpenASURF.this, "saving the picture", Toast.LENGTH_SHORT).show();
            isFinish = true;
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        mCamera.startPreview();
        // TODO Auto-generated method stub
    }
}; 

cv.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        if(mCamera != null) {
            mCamera.takePicture(null, null, pictureCallback);
            // let the system wait until finish taking the pictures.
            //while(isFinish == false) {
            try {
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //}
            Log.d("path", "mCurrentImagePath_over1 = " + mCurrentImagePath);
            Bitmap bmp = null;

            bmp = BitmapFactory.decodeFile(mCurrentImagePath);
            Log.d("path", "mCurrentImagePath_over2 = " + mCurrentImagePath);
        }

2 个答案:

答案 0 :(得分:1)

IMAGE_DIRECTORY是否正确?我希望它是/sdcard/DCIM/Camera,开头的正斜线。

更好的方法是以正确的方式获取图像路径:DIRECTORY_PICTURES

File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");

答案 1 :(得分:1)

无论您在takePicture()之后等待多长时间,onPictureTaken()只会在OnClick()返回后调用BitmapFactory.decodeFile(mCurrentImagePath); 回调:它们都使用应用主线程。

你可以打电话

onPictureTaken()

在您的onPictureTaken()中,或者您可以将活动从{{1}}发布到您的活动中。