如何在Android中显示用相机拍摄的图像

时间:2014-01-12 22:53:06

标签: android image camera

我正在尝试编写一个应用程序,该应用程序将使用原生Android Camera应用程序拍照,然后显示我刚刚在新活动中拍摄的照片。这是我的拍照方法。

private static File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
            );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
        }

        int t =5;
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

这有效;相机应用程序打开,图像被保存。但是,这是我的显示图像方法:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String j = MainActivity.mCurrentPhotoPath;
    Bitmap myBitmap = BitmapFactory.decodeFile(j);

    ImageView myImage = new ImageView(this);
    myImage.setImageBitmap(myBitmap);
    setContentView(myImage);
}

现在我测试了文件名路径是否被记录,而且是。字符串j确实有路径。但是,系统无法运行.decodeFile(String j)方法;它说不存在这样的文件。如何显示图像?

1 个答案:

答案 0 :(得分:1)

如果您使用的是原生相机,只要您使用onActivityResult()启动相机应用程序,就可以在startActivityForResult()中获得结果图片。然后,您可以按照以下方式获取对图片路径的引用(来自docs):

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Image captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Image saved to:\n" +
                     data.getData(), Toast.LENGTH_LONG).show();
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
        } else {
            // Image capture failed, advise user
        }
    }
}

然后,您可以通过Activity将此路径传递给新Intent,并相应地解码Bitmap