通过相机捕获图像并将其保存到图库中

时间:2018-10-21 08:09:34

标签: android image-gallery onactivityresult

我已经创建了一个按钮,单击该按钮可以打开相机并捕获图像。但随后它不会显示在我制作的imageview上,甚至不会保存在图库中。我想我写了正确的代码,但是流程似乎写错了。

public class MainActivity extends AppCompatActivity{


static final int REQUEST_IMAGE_CAPTURE=1;

ImageView img;
String mCurrentPhotoPath;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn=(Button)findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dispatchTakePictureIntent();
        }
    });
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==REQUEST_IMAGE_CAPTURE && requestCode==RESULT_OK )
    {
        Bundle extras=data.getExtras();
        Bitmap imageBitMap=(Bitmap) extras.get("data");
        img=(ImageView)findViewById(R.id.img);
        img.setImageBitmap(imageBitMap);

    }
}


private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}


}

2 个答案:

答案 0 :(得分:0)

在某些情况下,我们需要强制更新媒体光标,使其在移动图库中可见。因此,请尝试下面的代码段来强制更新您的媒体。

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(new File(...path of your image file)))); 

答案 1 :(得分:0)

正如我在您的代码中看到的那样,def application do [ extra_applications: [:logger, :ssl, :tortoise], mod: {Your.App, []} ] end 在任何地方都没有被调用。我认为您应该在createImageFile()内插入一些其他代码,并按以下方式进行操作:

dispatchTakePictureIntent

您应该在resources文件夹下的xml文件夹中创建一个名为“ file_paths.xml”的文件,如果尚未完成,您可以在其中编写以下代码:

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {


            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "YOUR_PACKAGE_NAME.provider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }

    }
}

还请记住在清单文件中声明提供者,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images"
        path="Android/data/YOUR_PACKAGE_NAME/files/Pictures" />
</paths>

请记住用您的真实包裹名称替换 YOUR_PACKAGE_NAME 。然后在您的 <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider> 方法中,以这种方式获取位图:

onActivityResult

img =(ImageView)findViewById(R.id.img);         img.setImageBitmap(bitmap);

逐步尝试,如有可能,请进行优化并提供反馈。在评论中要求澄清,但请先尝试。