在Android上拍摄并下载照片

时间:2012-10-07 18:14:07

标签: java android android-camera photo

我花了最后几个小时试图让这段代码成功拍照并将其下载到我手机的SD卡上。由于某种原因,它只是没有将照片保存到pictureFile。我不确定我做错了什么,但如果有人能给我一个提示,那就太好了。

public class PhotoTaker extends Activity {

    private Camera mCamera;
    private CameraPreview mCameraPreview;
    private File pictureFile;
    private CountDownTimer timer;
    public byte[] dataArray;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photoview);

        mCamera = getCameraInstance();
        mCameraPreview = new CameraPreview(this, mCamera);

        FrameLayout preview = (FrameLayout) findViewById(id.camera_preview);
        preview.addView(mCameraPreview);

        //Getting the actual picture
        final PictureCallback mPicture = new PictureCallback() {

            public void onPictureTaken(byte[] data, Camera camera) {
                       picturereFile = getOutputMediaFile();
                       #the pictureFils always is equal to null here and it doesn't write out anywhere
                       if (pictureFile == null){
                    return;
                }

                try {
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    dataArray = data;
                    fos.write(data);
                    fos.close();

                } catch (FileNotFoundException e) {
                    Log.d("filenotfound", null);


                } catch (IOException e) {
                    Log.d("ioexception", null);

                }

            }

        };


        //Adding listener
        final Button captureButton = (Button) findViewById(id.button_capture);
        captureButton.setOnClickListener(
                new View.OnClickListener() {

                    public void onClick(View v) {
                        mCamera.takePicture(null, null, mPicture);
                        timer.cancel();
                    }
                });

/** Create a File for saving the image */

private static File getOutputMediaFile(){

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

    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "IMG_"+ timeStamp + ".jpg");

    return mediaFile;
}

    }

以下是LogCat中的错误:

E/dalvikvm(524): Unable to open stack trace file '/data/anr/traces.txt': Permission denied

这应该由此解决但它仍然给我同样的错误:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

0 个答案:

没有答案