3

我正在尝试使用相机 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;
          } 
       }
    }
4

2 回答 2

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

        }
于 2013-02-23T11:23:53.037 回答
0

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

于 2013-02-23T11:32:33.200 回答