从android中的图库中获取图像

时间:2015-01-30 05:02:24

标签: android android-intent android-gallery

我一直在尝试从此应用中的图库中获取图像,然后点击按钮,我想上传到我的PHP服务器。

" selectedImagePath"为什么呢? 如果有人有解决方案,请帮助我!提前谢谢。

的onCreate()

img = (ImageView) findViewById(R.id.ImageView01);
        Button browse = (Button) findViewById(R.id.Button01);

        browse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
            }
        });

onActivityResult()

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                selectedImageUri = data.getData();
                System.out.println(selectedImageUri);
                selectedImagePath = getPath(selectedImageUri);//returns as null
                System.out.println("Image Path : " + selectedImagePath);
                img.setImageURI(selectedImageUri);
            }
        }
    }

的getPath()

public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

5 个答案:

答案 0 :(得分:7)

试试这个

@Override
public void onClick(View view) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, 0);
}

@Override
 protected void onActivityResult(int reqCode, int resCode, Intent data) {
    if(resCode == Activity.RESULT_OK && data != null){
        String realPath;
        // SDK < API11
        if (Build.VERSION.SDK_INT < 11) {
            realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
        }

        // SDK >= 11 && SDK < 19
        else if (Build.VERSION.SDK_INT < 19) {
            realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
        }

        // SDK > 19 (Android 4.4)
        else {
            realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
        }
        System.out.println("Image Path : " + realPath);
    }
}


public class RealPathUtil {

    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API19(Context context, Uri uri){
        String filePath = "";
        String wholeID = DocumentsContract.getDocumentId(uri);

         String id = wholeID.split(":")[1];

         String[] column = { MediaStore.Images.Media.DATA };     

         // where id is equal to             
         String sel = MediaStore.Images.Media._ID + "=?";

         Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                                   column, sel, new String[]{ id }, null);

         int columnIndex = cursor.getColumnIndex(column[0]);

         if (cursor.moveToFirst()) {
             filePath = cursor.getString(columnIndex);
         }   
         cursor.close();
         return filePath;
    }


    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
          String[] proj = { MediaStore.Images.Media.DATA };
          String result = null;

          CursorLoader cursorLoader = new CursorLoader(
                  context, 
            contentUri, proj, null, null, null);        
          Cursor cursor = cursorLoader.loadInBackground();

          if(cursor != null){
           int column_index = 
             cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           result = cursor.getString(column_index);
          }
          return result;  
    }

    public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
               String[] proj = { MediaStore.Images.Media.DATA };
               Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
               int column_index
          = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
               cursor.moveToFirst();
               return cursor.getString(column_index);
    }
}

getRealPath类的代码不是我的,我不记下网站。

答案 1 :(得分:0)

获取数据后,首先从该路径创建文件,然后将该文件的路径作为&#34; selectedImagePath&#34;。然后,您将获得外部存储上的实际图像路径:尝试以下代码:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            selectedImageUri = data.getData();
            File myFile = new File(selectedImageUri);
            System.out.println(selectedImageUri);
            selectedImagePath = myFile.getPath();
            System.out.println("Image Path : " + selectedImagePath);
            img.setImageURI(selectedImageUri);
        }
    }
}

答案 2 :(得分:0)

试试这段代码,

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            System.out.println("Image Path : " + selectedImagePath);
            img.setImageURI(selectedImageUri);
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

答案 3 :(得分:0)

尝试以下代码

if (resultCode == RESULT_OK) {
    if (requestCode == SELECT_PICTURE) {
            Uri uri = data.getData();
            String[] filepath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(uri, filepath, null,
                    null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filepath[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            System.out.println("Image Path : " + filePath);

        }

答案 4 :(得分:0)

我花了一些时间在这个问题上,最终我找到了完全有效的解决方案()。

:一种。 它取自 cordova-plugin-camera ,可在此处找到:

public static String getRealPath(final Uri uri, final Context context) {
    String realPath = null;

    if (Build.VERSION.SDK_INT < 11) {
        realPath = FileHelper.getRealPathFromURI_BelowAPI11(context, uri);

        // SDK >= 11
    } else {
        realPath = FileHelper.getRealPathFromURI_API11_And_Above(context, uri);
    }

    return realPath;
}

[FileHelper.class]中提供了两种方法: https://github.com/apache/cordova-plugin-camera/blob/06d609cfa4871b4a2811f5a8f7f0a822733209b9/src/android/FileHelper.java

我不想复制代码,而是提供链接,因为解决方案非常复杂。 /我认为他们可以过期,但希望他们不会/

<强>乙 以下是示例项目[RealPathUtil.java]源代码的链接:https://github.com/hmkcode/Android/blob/master/android-show-image-and-path/src/com/hmkcode/android/image/RealPathUtil.java

<强>下进行。 这里的另一个问题没有引起太多关注。 [Stack Overflow Post]:https://stackoverflow.com/a/36714242