相机意图创建空照片

3

我正在尝试使用相机意图拍照,但是存储的照片为空(大小为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个回答

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 :) - Mudassar Shaheen
抱歉出了些问题,不用担心,继续享受编码的乐趣吧。 - Mudassar Shaheen

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接