2016-04-11 36 views
1

我試圖設置拍攝到ImageButton scr的照片的縮略圖。下面的代碼可以很好地處理圖片並將其存儲在圖庫中,但「Bitmap imageBitmap =(Bitmap)extras.get(」data「);」返回null。 任何人都可以請解釋爲什麼?數據在拍照時返回爲空

private void openCamera() { 
    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 
     photoFile = null; 
     try { 
      photoFile = createImageFile(); 
     } catch (IOException ex) { 
      // Error occurred while creating the File 
      Log.i("Camera log", "Failed:" + ex.toString()); 
     } 
     // Continue only if the File was successfully created 
     if (photoFile != null) { 
      takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
        Uri.fromFile(photoFile)); 

      startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); 
     } 
    } 
} 

private void galleryAddPic() { 
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
    File f = new File(mCurrentPhotoPath); 
    Uri contentUri = Uri.fromFile(f); 
    mediaScanIntent.setData(contentUri); 
    this.sendBroadcast(mediaScanIntent); 
} 


@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { 
     Bundle extras = data.getExtras(); 
     Bitmap imageBitmap = (Bitmap) extras.get("data"); 
     cameraBtn.setImageBitmap(imageBitmap); 
     galleryAddPic(); 
    } 
} 
+1

參考'photoFile'對象,其中包含捕獲的圖像。 –

回答

1

當您設置MediaStore.EXTRA_OUTPUT時,您必須從此URL獲取照片。

實施例:

if(photoFile!=null){ 
BitmapFactory.Options bmOptions = null; 
bmOptions = new BitmapFactory.Options(); 
Bitmap mBitmap = BitmapFactory.decodeFile(photoFile.getPath(), bmOptions); 
} 
else{ 
Bundle extras = data.getExtras(); 
     Bitmap imageBitmap = (Bitmap) extras.get("data"); 
     cameraBtn.setImageBitmap(imageBitmap); 
     galleryAddPic(); 
} 
+0

謝謝米格爾。通過在答案的decodeFile(photoFile,bmOptions)中添加'getPath()',解決了問題。非常感激。 :) –

0

誰能請解釋一下爲什麼?

您提供了EXTRA_OUTPUT。您的圖片應存儲在您指定的位置。如果你做不是提供EXTRA_OUTPUT,然後extras.get("data")應該有你的Bitmap(至少如果你的應用程序使用的相機應用程序沒有錯誤)。