2009-11-27 48 views
3

我試圖獲取在手機上本地保存的圖像的字節數組。我使用的代碼:Android獲取本地文件字節

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.upload); 

    // Look in the Device 
    startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), 1); 
    // Look in the SD Card 
    // startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI), 1); 
} 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (requestCode == 1) 
    if (resultCode == Activity.RESULT_OK) { 
     Uri selectedImage = data.getData(); 
     Cursor Cur = Upload.this.managedQuery(selectedImage, null, null, null,null); 
     if (Cur.moveToFirst()) { 
      File Img = new File(selectedImage.getPath()); 
      long Length = Cur.getLong(Cur.getColumnIndex(ImageColumns.SIZE)); 
      byte[] B = new byte[(int)Length-1]; 
      FileInputStream ImgIs; 
      try { 
      ImgIs = new FileInputStream(Img); 
      ImgIs.read(B); 
      } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     int i = B.length; 
     } 
    } 
} 

但它拋出一個FileNotFound exception

ImgIs = new FileInputStream(Img) 

我怎樣才能得到字節?

+0

由於我回答了我自己的問題,我應該在這裏留下問題還是刪除它? – JoshKraker 2009-11-27 05:27:02

回答

0

沒關係,我找到了答案,看到http://www.mail-archive.com/[email protected]/msg66448.html

Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
cursor.moveToFirst(); 

int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
String absoluteFilePath = cursor.getString(idx); 
FileInputStream fis = new FileInputStream(absoluteFilePath); 
0

這是另一種方法,我在我的最後一個項目中使用:

bitmap.compress(CompressFormat.JPEG, 100, outputStream); 

在上面的代碼中,我寫的位圖的內容的OutputStream與100%的質量。 希望這有助於