2016-07-23 77 views
0

我在Android的编程初学者,我只是想显示通过相机拍摄的图像,这里是我的代码位图是返回NULL在Android的

private File createImageFile() throws IOException { 
    // Create an image file name 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    String imageFileName = "JPEG_" + timeStamp + "_"; 
    File storageDir = getExternalFilesDir(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) { 
      // Error occurred while creating the File 
     } 
     // Continue only if the File was successfully created 
     if (photoFile != null) { 
      fileUri = FileProvider.getUriForFile(this, 
        "com.example.android.fileprovider", 
        photoFile); 
      takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 
      startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); 
     } 
    } 
} 
private void previewSavedImage() { 
    try { 
     // hide video preview 
     videoPreview.setVisibility(View.GONE); 

     imgPreview.setVisibility(View.VISIBLE); 

     // bimatp factory 
     BitmapFactory.Options options = new BitmapFactory.Options(); 

     // downsizing image as it throws OutOfMemory Exception for larger 
     // images 
     options.inSampleSize = 2; 

     String path = fileUri.getPath(); 

     //File img_file = new File(getFilesDir(), path); 



     final Bitmap bitmap = BitmapFactory.decodeFile(path, options); 

     imgPreview.setImageBitmap(bitmap); 
    } catch (NullPointerException e) { 
     e.printStackTrace(); 
    } 
} 

在上面的代码中的位图总是返回没有因为我的无法显示图像。我执行任务吗?

+0

您会收到一个错误? –

+0

否,但“位图”值为空。 – Yogesh

+0

我试过这段代码,但没有抛出OutOfMemoryException异常。 我现在只是担心android是否将捕获的图像存储到指定的位置,我如何验证? – Yogesh

回答

1

最后我解决了这个问题。问题是与mCurrentPhotoPath中的“file:”字符串,我只需要在decodeFile方法中使用它之前将其删除。

Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath.replace("file:", "")); 
+0

那你为什么把它放在那里?如果你需要的话,你应该使用“file://”。 – greenapps

+0

好赶上!这是对细节的关注。 –

+0

我会删除它。我只是遵循文档,并认为它稍后可能会有用。 – Yogesh