定制相机应用程序不保存图像

时间:2014-08-25 11:41:56

标签: android android-camera

我已根据Google的相机指南将此代码放在一起。相机应用程序工作,但点击按钮时会发生注意。也许注意到应该发生,我只是了解Camera API,但我想它应该将图像保存在SD卡上,但没有任何东西存在。我在这段代码中遗漏了什么:

public class NewItemCamera extends Activity {

private Camera mCamera;
private NewItemSurfaceView mPreview;
Button captureButton;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

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

    captureButton = (Button) findViewById(R.id.buttonClick);

    // Create an instance of Camera
    mCamera = getCameraInstance();
    mCamera.setDisplayOrientation(90);

    // Create our Preview view and set it as the content of our activity.
    mPreview = new NewItemSurfaceView(this, mCamera);
    FrameLayout preview = (FrameLayout) findViewById(R.id.flCamera);
    preview.addView(mPreview);

    // Add a listener to the Capture button
    captureButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // get an image from the camera
            mCamera.takePicture(null, null, mPicture);

        }
    });
}

/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance() {
    Camera c = null;
    try {
        c = Camera.open(); // attempt to get a Camera instance
    } catch (Exception e) {
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
}

private PictureCallback mPicture = new PictureCallback() {

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

        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (pictureFile == null) {
            Log.d("Camera error",
                    "Error creating media file, check storage permissions: ");
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d("Camera error", "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d("Camera error", "Error accessing file: " + e.getMessage());
        }
    }
};

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.i("MyCameraApp", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

}

1 个答案:

答案 0 :(得分:-1)

试试这个

private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;

private void selectImage() {

AlertDialog.Builder builder = new AlertDialog.Builder(
            ProfileActivity.this);
    // builder.setTitle("Choose Image Source");
    builder.setItems(new CharSequence[] { "Take a Photo",
            "Choose from Gallery" },
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                    case 0:
                        Intent intent1 = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        intent1.putExtra(MediaStore.EXTRA_OUTPUT,
                                setImageUri());
                        startActivityForResult(intent1, CAPTURE_IMAGE);
                        break;
                    case 1:
                        // GET IMAGE FROM THE GALLERY
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(
                                Intent.createChooser(intent, ""),
                                PICK_IMAGE);
                        break;
                    default:
                        break;
                    }
                }
            });
    builder.show();
}


 public Uri setImageUri() {

File file = new File(Environment.getExternalStorageDirectory(), "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
 }


  public String getImagePath() {
    return imgPath;
 }

onActivityForResultSetMethod

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (resultCode != Activity.RESULT_CANCELED) {
    if (requestCode == PICK_IMAGE) {
        selectedImagePath = getAbsolutePath(data.getData());
        System.out.println("path" + selectedImagePath);
        imageView.setImageBitmap(decodeFile(selectedImagePath));

    } else if (requestCode == CAPTURE_IMAGE) {
        selectedImagePath = getImagePath();
        System.out.println("path" + selectedImagePath);
        imageView.setImageBitmap(decodeFile(selectedImagePath));


    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
  }
 }


 public Bitmap decodeFile(String path) {
 try {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, o);
    // The new size we want to scale to
    final int REQUIRED_SIZE = 70;

    // Find the correct scale value. It should be the power of
    // 2.
    int scale = 1;
    while (o.outWidth / scale / 2 >= REQUIRED_SIZE
            && o.outHeight / scale / 2 >= REQUIRED_SIZE)
        scale *= 2;

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
    e.printStackTrace();
}
return null;
 }


public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };

Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
} else
    return null;
}