使用前置摄像头Android拍照时出错

时间:2015-09-04 13:20:02

标签: android android-camera

我正在尝试使用前置摄像头拍照。单击按钮后,应用程序将拍摄照片并保存,而不显示照片和相机视图。

camera.takePicture不起作用,我收到了这个错误:

  

引起:java.lang.RuntimeException:takePicture失败

以下代码有什么问题?

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


import android.os.Bundle;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
    Button button = (Button) findViewById(R.id.buttonCapture);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            camera.takePicture(null, null, mPicture);
        }
    });

}

private Camera.PictureCallback mPicture = new Camera.PictureCallback(){
    @Override
    public void onPictureTaken(byte[] data, Camera camera){
        File pictureFile = getOutputMediaFile();

        if(pictureFile == null){
            Log.d("TEST", "Error creating media file, check storage permissions");
            return;
        }
        try{
            Log.d("TEST","File created");
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        }catch(FileNotFoundException e){
            Log.d("TEST","File not found: "+e.getMessage());
        } catch (IOException e){
            Log.d("TEST","Error accessing file: "+e.getMessage());
        }
    }
};

private File getOutputMediaFile(){

    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");

    if(!mediaStorageDir.exists()){
        if(!mediaStorageDir.mkdirs()){
            return null;
        }
    }
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg");

    return mediaFile;
}}

权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />

0 个答案:

没有答案