Android从图库中选择图像

时间:2015-01-03 13:10:59

标签: android image-processing

在片段中,我正在调用图库这样的意图:

         // Create the Intent for Image Gallery.
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, MainActivity.LOAD_IMAGE_RESULTS);

在主要活动中,我使用以下代码处理结果:

public static int LOAD_IMAGE_RESULTS = 1;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.w("reqestCode:",""+requestCode);
    if(requestCode == LOAD_IMAGE_RESULTS && data != null && data.getData() != null) {
        Uri _uri = data.getData();

        //User had pick an image.
        Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
        cursor.moveToFirst();

        //Link to the image
        final String imageFilePath = cursor.getString(0);
        Log.w("ImageFile",imageFilePath);
        cursor.close();
    }
}

但在onActivityResult中requestCode返回196609值。所以我的代码无效。我该如何解决?

3 个答案:

答案 0 :(得分:0)

看起来问题与您创建的Intent有关。尝试这样的事情:

                pictureActionIntent = new Intent(
                        Intent.ACTION_GET_CONTENT, null);
                pictureActionIntent.setType("image/*");
                pictureActionIntent.putExtra("return-data", true);
                startActivityForResult(pictureActionIntent,
                        GALLERY_PICTURE);

有关详细信息,请查看this answer。

答案 1 :(得分:0)

你说你是从Fragment打来的。你有没有试过在这两个地方听onActivityResultActivity以及Fragment?这值得一试。 :)

答案 2 :(得分:0)

试试这个代码它会起作用 //开始活动

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
                Intent.createChooser(intent, "Select Picture"),
                GALLERY_INTENT_CALLED);

//在onactivityresult中获取位图

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == GALLERY_INTENT_CALLED) {
            if (null == data)
                return;
            String selectedImagePath;
            Uri selectedImageUri = data.getData();
            // MEDIA GALLERY
             Bitmap bitmap = BitmapFactory.decodeFile(ImageFilePath.getPath(
                    getApplicationContext(), selectedImageUri));
            ivProfileImage.setImageBitmap(bitmap);

        }
    }
}