2013-02-23 73 views
3

我試圖用相機意圖拍照,但寫入存儲的圖片是空的(大小:0字節)。有人能告訴我我的代碼有什麼問題嗎?Camera Intent創建空圖片

public void onClick(View arg0) { 
    switch (arg0.getId()) {  
    case R.id.btnImageCapture: 
    preinsertedUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues()); 
     Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);   
     startActivityForResult(intent, OPEN_CAMERA); 
     break; 
     } 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch(requestCode){ 
    case OPEN_CAMERA: 
     if (resultCode != 0 && data != null) { 
       Uri imageUri = null; 
       if (data != null){ 
         imageUri = data.getData(); 
        } 
        if(imageUri == null && preinsertedUri != null){ 
        imageUri = preinsertedUri; 
        } 
      String[] filePathColumn = { MediaStore.Images.Media.DATA }; 
       Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null); 
       int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
       cursor.moveToFirst(); 
       filePath = cursor.getString(columnIndex); 
        break; 
      } 
     } 
    } 

回答

3

試試這個代碼,它的工作對我來說

case OPEN_CAMERA: 
      if (resultCode == RESULT_OK) { 
      Bitmap photo = (Bitmap) data.getExtras().get("data"); 
      saveBitmap(photo, pathToStrore); 
            } 
     break; 

    public void saveBitmap(Bitmap photo, String path) { 
      ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
      photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 

      // you can create a new file name "test.jpg" in sdcard folder. 
      File f = new File(path); 
      try { 
       f.createNewFile(); 
       FileOutputStream fo = new FileOutputStream(f); 
       fo.write(bytes.toByteArray()); 

       // remember close de FileOutput 
       fo.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      // write the bytes in file 

     } 
+0

你爲我做過的一天。 :D謝謝! – 2013-02-23 11:40:57

+0

也給我的答案加1 :) – 2013-02-23 12:05:37

+0

我沒有足夠的聲望投票了。 ;( – 2013-02-23 12:11:03