【问题标题】:Custom camera app not saving image自定义相机应用程序不保存图像
【发布时间】:2014-08-25 11:41:56
【问题描述】:

我根据 Google 的相机指南整理了这段代码。相机应用程序工作,但注意发生在按钮点击。也许应该注意到,我刚刚开始了解相机 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;
}

}

【问题讨论】:

  • logcat 没有错误?
  • 我无法使用 logcat,因为我在工作,而我的笔记本电脑由于某种原因无法识别我的手机。我在手机上传输 apk 并以这种方式进行测试。按钮单击不会导致应用程序崩溃,因此我认为不存在重大错误。
  • 最好建立一个体面的开发环境,否则它会让你长出很多白发。您需要很长时间才能弄清楚为什么在没有记录的情况下会不会发生某些事情。当然它不会崩溃 - 你吞下所有异常并将它们写入 logcat。如果您可以阅读 logcat,那就没问题了。
  • 好的 Fildor,谢谢。我回家后试试。顺便说一句,我已经安装了 genymotion 模拟器并尝试了它。它工作正常,图像已保存。你明白了吞下异常的意思,仍然是android noob,对不起:)
  • 您找到解决方案了吗?我有同样的问题。

标签: android android-camera


【解决方案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;
 }

onActivityForResultSet方法

 @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;
}

【讨论】:

  • 你能详细说明他为什么要“试试这个”吗?
  • 它的工作是从相机拍照并保存在 SD 卡中并获取该照片的路径..
  • 您的解决方案不包括自定义相机应用。这是使用与 OP 的问题无关的现有应用程序。
猜你喜欢
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多