2013-10-24 54 views
0

我正在尝试使用安卓相机拍摄照片并将其保存到手机的相册中。我想我迷路了,但我似乎无法找到我的错误。有人能帮助我吗?我在android上很新手。照片不显示到图库

代码来调用摄像头

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
        String uriToFileInExternalStorage = null; 
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriToFileInExternalStorage); 
        startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); 

代码来处理照片,并告诉它去画廊。这里给出

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
      if (requestCode == CAMERA_PIC_REQUEST) { 
       //check if camera has taken picture by checking request code 

       Toast.makeText(MainActivity.this, "Photo Captured", Toast.LENGTH_SHORT).show(); 


       Uri mPath=data.getData(); 
       Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 

        mediaScanIntent.setData(mPath); 
        this.sendBroadcast(mediaScanIntent); 

      } 
     } 
+0

示例代码基于https://developer.android.com/training/camera/photobasics.html#TaskGallery – user2872261

回答

2

try代码:Add the Photo to a Gallery

Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
File f = new File(mCurrentPhotoPath); 
Uri contentUri = Uri.fromFile(f); 
mediaScanIntent.setData(contentUri); 
this.sendBroadcast(mediaScanIntent); 

我建议您下载例子PhotoIntentActivity阅读并了解如何获取mCurrentPhotoPath值。

+0

我累了,它给了我错误。 “mCurrentPhotoPath无法解析为变量” – user2872261

+0

@ user2872261检查更新的代码。您正在做的错误是您没有捕获具有实际路径名称的图像。 –

+0

感谢您的回复。 如何捕捉路径名称的图像?我认为captureImageUri是路径名称。我如何获取mCurrentPhotoPath的字符串?我得到一个null mCurrentPhotoPath ...什么给mCurrentPhotoPath一个字符串? – user2872261

0

您需要的值设置为这个uriToFileInExternalStorage

示例代码:

fileName = "image_" + String.valueOf(numImages) + ".jpg"; 

File output = new File(direct + File.separator + fileName); // create 
                    // output 
while (output.exists()) { // while the file exists 
    numImages++; // increment number of images 
    fileName = "image_" + String.valueOf(numImages) + ".jpg"; 
    output = new File(outputFolder, fileName); 
} 

uriToFileInExternalStorage = Uri.fromFile(output); 
+0

我不明白:(对不起,我是一个新手。我不知道从哪里开始...我在哪里把这个“Uri mPath = data.getData();”的值? – user2872261

+0

不,这是你的摄像头调用方法的变化..你已经将它设置为空。 – Vinay

1

这将相机拍摄

MediaScannerConnection.scanFile的活动成果应用于所有Android版本的工作( this,new String [] {file.getPath()},new String [] {“image/jpeg”},null);

+0

谢谢,它的工作!我不知道为什么,但发送与Intent.ACTION_MEDIA_SCANNER_SCAN_FILE广播最常见的方法不适用于我(Nexus 5倍,牛轧糖7.1),但你的方法帮助! –