android 如何设置图像上传仅为jpg和png文件?

gg58donl  于 2022-12-09  发布在  Android
关注(0)|答案(4)|浏览(396)

这里是我使用的代码,它的工作很好,但如何我只设置文件类型为jpg和png和不允许/不显示任何其他图像在画廊

private void ButtonOnClick(object sender, EventArgs eventArgs) {
    Intent = new Intent();
    Intent.SetType("image/*");
    Intent.SetAction(Intent.ActionGetContent);
    StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
}

#endregion

#region Get the Path of Selected Image
private string GetPathToImage(Uri uri) {
    string path = null;
    // The projection contains the columns we want to return in our query.
    string[] projection = new[] { 
            Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
    using (ICursor cursor = ManagedQuery(uri, projection, null, null, null)) {
        if (cursor != null) {
            int columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
            cursor.MoveToFirst();
            path = cursor.GetString(columnIndex);
        }
    }
    return path;
}
#endregion

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) {
    // For single image Selection
    if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null)) {
        Uri uri = data.Data;
        _imageView.SetImageURI(uri);
        path = GetPathToImage (uri);
    }
}
3htmauhk

3htmauhk1#

我认为所有给出的答案都是错误的。要求是允许jpg和png文件。这只允许选择给定的文件类型。
首先创建mimeTypes数组,包括所有允许的文件类型。
然后把它放在意想加贺的身上。
下面是代码。

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
String [] mimeTypes = {"image/png", "image/jpg","image/jpeg"};
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_GET_SINGLE_FILE);
41ik7eoe

41ik7eoe2#

对jpeg使用setType
intent.setType("image/jpeg")intent.setType("image/jpg")
或用于png
intent.setType("image/png")

vbopmzt1

vbopmzt13#

使用此Intent.setType("image/jpg");代替Intent.setType("image/*");

avkwfej4

avkwfej44#

我知道我回答得晚了,但对我有效的解决方案我只想分享。

Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT); // opens shared file explorer
    galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
    String[] mimeTypes = {"image/jpeg", "image/png"};  // /jpeg will support both jpg and jpeg files
    galleryIntent.setType("image/jpeg|image/png");  // I had to include both setType and putExtra for my code to work correctly
    galleryIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
    pickImageFromGalleryForResult.launch(galleryIntent);  // you can replace this line with your startActivityForResult() here

试试看,告诉我它是否适合您的用例。

相关问题