android pick images from gallery

前端 未结 10 1711
太阳男子
太阳男子 2020-11-22 13:53

I want to create a picture chooser from gallery. I use code

 intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTE         


        
相关标签:
10条回答
  • 2020-11-22 14:15

    I have same problem .I use this codes

    addIntent

     Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Tack Image"), PICK_PHOTO);
    

    add onActivityResult

     @Override
      public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PHOTO && resultCode == Activity.RESULT_OK) {
          if (data == null) {
          //error
            return;
          }
          try {
            Uri uri = data.getData();
            File file = FileUtil.from(currentActivity, uri);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    

    FileUtil class

    import android.content.Context;
    import android.database.Cursor;
    import android.net.Uri;
    import android.provider.OpenableColumns;
    import android.util.Log;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    public class FileUtil {
      private static final int EOF = -1;
      private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
    
      private FileUtil() {
    
      }
    
      public static File from(Context context, Uri uri) throws IOException {
        InputStream inputStream = context.getContentResolver().openInputStream(uri);
        String fileName = getFileName(context, uri);
        String[] splitName = splitFileName(fileName);
        File tempFile = File.createTempFile(splitName[0], splitName[1]);
        tempFile = rename(tempFile, fileName);
        tempFile.deleteOnExit();
        FileOutputStream out = null;
        try {
          out = new FileOutputStream(tempFile);
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        }
        if (inputStream != null) {
          copy(inputStream, out);
          inputStream.close();
        }
    
        if (out != null) {
          out.close();
        }
        return tempFile;
      }
    
      private static String[] splitFileName(String fileName) {
        String name = fileName;
        String extension = "";
        int i = fileName.lastIndexOf(".");
        if (i != -1) {
          name = fileName.substring(0, i);
          extension = fileName.substring(i);
        }
    
        return new String[]{name, extension};
      }
    
      private static String getFileName(Context context, Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
          Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
          try {
            if (cursor != null && cursor.moveToFirst()) {
              result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            if (cursor != null) {
              cursor.close();
            }
          }
        }
        if (result == null) {
          result = uri.getPath();
          int cut = result.lastIndexOf(File.separator);
          if (cut != -1) {
            result = result.substring(cut + 1);
          }
        }
        return result;
      }
    
      private static File rename(File file, String newName) {
        File newFile = new File(file.getParent(), newName);
        if (!newFile.equals(file)) {
          if (newFile.exists() && newFile.delete()) {
            Log.d("FileUtil", "Delete old " + newName + " file");
          }
          if (file.renameTo(newFile)) {
            Log.d("FileUtil", "Rename file to " + newName);
          }
        }
        return newFile;
      }
    
      private static long copy(InputStream input, OutputStream output) throws IOException {
        long count = 0;
        int n;
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        while (EOF != (n = input.read(buffer))) {
          output.write(buffer, 0, n);
          count += n;
        }
        return count;
      }
    }
    

    and you must add provider_paths.xml to xml folder like image

    provider_paths.xml

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path name="external_files" path="."/>
    </paths>
    

    and finaly add below in AndroidManifest.xml

    <application
    ...>
    
    ...
          <provider
              android:name="androidx.core.content.FileProvider"
              android:authorities="${applicationId}.provider"
              android:exported="false"
              android:grantUriPermissions="true">
              <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
            </provider>
    ...
    </application>
    

    I hope I helped

    0 讨论(0)
  • 2020-11-22 14:18

    You can use this method to pick image from gallery. Only images will be displayed.

    public void pickImage() {
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("outputX", 256);
        intent.putExtra("outputY", 256);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 1);
    }
    

    and override onActivityResult as

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode != RESULT_OK) {
                return;
            }
            if (requestCode == 1) {
                final Bundle extras = data.getExtras();
                if (extras != null) {
                    //Get image
                    Bitmap newProfilePic = extras.getParcelable("data");
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-22 14:19

    Here is a full example for request permission (if need), pick image from gallery, then convert image to bitmap or file

    AndroidManifesh.xml

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    

    Activity

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            button_pick_image.setOnClickListener {
                pickImage()
            }
        }
    
        private fun pickImage() {
            if (ActivityCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                val intent = Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI
                )
                intent.type = "image/*"
                intent.putExtra("crop", "true")
                intent.putExtra("scale", true)
                intent.putExtra("aspectX", 16)
                intent.putExtra("aspectY", 9)
                startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE)
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                    READ_EXTERNAL_STORAGE_REQUEST_CODE
                )
            }
        }
    
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
            if (requestCode == PICK_IMAGE_REQUEST_CODE) {
                if (resultCode != Activity.RESULT_OK) {
                    return
                }
                val uri = data?.data
                if (uri != null) {
                    val imageFile = uriToImageFile(uri)
                    // todo do something with file
                }
                if (uri != null) {
                    val imageBitmap = uriToBitmap(uri)
                    // todo do something with bitmap
                }
            }
        }
    
        override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
            when (requestCode) {
                READ_EXTERNAL_STORAGE_REQUEST_CODE -> {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // pick image after request permission success
                        pickImage()
                    }
                }
            }
        }
    
        private fun uriToImageFile(uri: Uri): File? {
            val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = contentResolver.query(uri, filePathColumn, null, null, null)
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndex(filePathColumn[0])
                    val filePath = cursor.getString(columnIndex)
                    cursor.close()
                    return File(filePath)
                }
                cursor.close()
            }
            return null
        }
    
        private fun uriToBitmap(uri: Uri): Bitmap {
            return MediaStore.Images.Media.getBitmap(this.contentResolver, uri)
        }
    
        companion object {
            const val PICK_IMAGE_REQUEST_CODE = 1000
            const val READ_EXTERNAL_STORAGE_REQUEST_CODE = 1001
        }
    }
    

    Demo
    https://github.com/PhanVanLinh/AndroidPickImage

    0 讨论(0)
  • 2020-11-22 14:19

    For only pick from local add this :

            i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)
    

    And this working nice :

        val i = Intent(Intent.ACTION_GET_CONTENT,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        i.type = "image/*"
        i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)
        startActivityForResult(Intent.createChooser(i,"Select Photo"),pickImageRequestCode)
    
    0 讨论(0)
  • 2020-11-22 14:20

    If you are only looking for images and multiple selection.

    Look @ once https://stackoverflow.com/a/15029515/1136023

    It's helpful for future.I personally feel great by using MultipleImagePick.

    0 讨论(0)
  • 2020-11-22 14:20

    U can do it easier than this answers :

    Uri Selected_Image_Uri = data.getData();
    ImageView imageView = (ImageView) findViewById(R.id.loadedimg);
    imageView.setImageURI(Selected_Image_Uri);
    
    0 讨论(0)
提交回复
热议问题