2011-11-28 41 views
0

我正在構建一個應用程序,拍攝一張照片,然後通過電子郵件發送。爲此,我必須將其保存到設備的內存中。我得到的問題是,當應用程序寫我的文件,它崩潰的代碼這一行:如何正確地將照片寫入內存並獲取URI(蜂窩)?

intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(Environment.getExternalStorageDirectory())); 

下你的整個功能和代碼:

private void takePicture(){ 
    File outputFile = new File(Environment.getExternalStorageDirectory(), "image.jpg"); 
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(Environment.getExternalStorageDirectory())); 
    startActivityForResult(intent, 1); 
} 

public void onActivityResult(int requestCode, int resultCode, Intent data){ 
     if(requestCode == CAMERA_PIC_REQUEST && resultCode == Activity.RESULT_OK){ 
      picture = (Bitmap) data.getExtras().get("data"); 
      pictureView.setImageBitmap(picture); 

      ContentValues values = new ContentValues(); 
      values.put(Images.Media.TITLE, "Picture"); 
      values.put(Images.Media.BUCKET_ID, "picture_ID"); 
      values.put(Images.Media.DESCRIPTION, ""); 
      values.put(Images.Media.MIME_TYPE, "image/jpeg"); 

      pictureUri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); 
      OutputStream outstream; 

      try{ 
       outstream = getContentResolver().openOutputStream(pictureUri); 
       picture.compress(Bitmap.CompressFormat.JPEG, 100, outstream); 
       outstream.close(); 
      }catch(FileNotFoundException e){ 

      } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     } 
    } 

如果我評論這一線,應用程序不會崩潰了。我需要獲取照片的URI,然後才能發送電子郵件。

任何幫助從你們更有經驗的那裏將不勝感激。

回答

1

試試這個

Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
File path = new File("/mnt/sdcard/YourDirectory"); 
path.mkdirs(); 
String fileName = "yourfile.jpg"; 
File file = new File(path, name); 
camera.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,Uri.fromFile(file)); 
startActivityForResult(camera, PICTURE_RESULT); 



@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (PICTURE_RESULT == requestCode && Activity.RESULT_OK == resultCode) { 
    if (android.os.Environment.getExternalStorageState().equals(
       android.os.Environment.MEDIA_MOUNTED)) { 
      ////////// TASK TODO After result ////////// 
     } else { 
     Toast.makeText(this, "sdcard not available", Toast.LENGTH_LONG).show(); 
     } 
    } 
}