Camera Intent创建空白图片

时间:2013-02-23 11:11:34

标签: android android-intent camera

我正在尝试使用相机Intent拍照,但写入存储空间的图片为空(大小:0字节)。有人能告诉我我的代码有什么问题吗?

    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;
          } 
       }
    }

2 个答案:

答案 0 :(得分: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

        }

答案 1 :(得分:0)

试试我发布的代码:https://stackoverflow.com/a/14965840/1291514。它还有一种方法可以将图片保存到onActivityResult中的另一个位置。