简体   繁体   English

在Android中从图库获取图像

[英]Getting Image from gallery in android

I've been trying to get an image from gallery in this app and then on a button click I want to upload to my PHP server. 我一直在尝试从此应用程序的图库中获取图像,然后在一个按钮上单击“我想上传到我的PHP服务器”。

The "selectedImagePath" comes as null why? 为什么“ selectedImagePath”为null? If anyone has a solutions please help me! 如果有人有解决方案,请帮助我! Thanks in advance. 提前致谢。

onCreate() 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() 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() 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);
    }

try this 尝试这个

@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);
    }
}

the code for getRealPath class is not mine, I din't write down the website. getRealPath类的代码不是我的,我没有写下网站。

When you get the data, create file from that path first and then get that file's path as "selectedImagePath". 当您获取数据时,首先从该路径创建文件,然后以“ selectedImagePath”的形式获取该文件的路径。 Then you will get actual path of image on external storage: Try below code: 然后,您将获得外部存储上图像的实际路径:请尝试以下代码:

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);
        }
    }
}

try this code, 试试这个代码,

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);
}

Try below code 试试下面的代码

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);

        }

I've spent some time on this problem and eventually I found the fully working solution(). 我花了一些时间在这个问题上,最终我找到了可以正常工作的解决方案()。

A. It's taken from cordova-plugin-camera which can be found here: 它取自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;
}

both methods are provided in [FileHelper.class]: https://github.com/apache/cordova-plugin-camera/blob/06d609cfa4871b4a2811f5a8f7f0a822733209b9/src/android/FileHelper.java 两种方法都在[FileHelper.class]中提供: https : //github.com/apache/cordova-plugin-camera/blob/06d609cfa4871b4a2811f5a8f7f0a822733209b9/src/android/FileHelper.java

I don't want to duplicate the code, links are provided instead because solutions are quite complex. 我不想重复代码,而是提供链接,因为解决方案非常复杂。 /I consider the fact that they could expire but hoping they won't/ /我认为它们可能会过期,但希望它们不会/

B. Here is a link to the source code of a sample project [RealPathUtil.java]: https://github.com/hmkcode/Android/blob/master/android-show-image-and-path/src/com/hmkcode/android/image/RealPathUtil.java B.这是示例项目[RealPathUtil.java]的源代码的链接: https : //github.com/hmkcode/Android/blob/master/android-show-image-and-path/src/com/ hmkcode / android / image / RealPathUtil.java

C. Another question in here that didn't find much attention. C.这里的另一个问题并没有引起太大关注。 [Stack Overflow Post]: https://stackoverflow.com/a/36714242 [Stack Overflow Post]: https//stackoverflow.com/a/36714242

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM