如何设置图片上传仅限于jpg和png文件?

6

这里是我正在使用的代码,它运行得很好,但是如何仅将文件类型设置为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);
    }
}
4个回答

6

我认为所有给出的答案都是错误的。要求允许选择jpg和png文件。这个方法只允许选择给定的文件类型。

首先创建一个包含所有允许的文件类型的mimeTypes数组。
然后将它放入意图extras中。

以下是代码。

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

0

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

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

试一下,告诉我它是否适用于你的使用情况。


0
使用这个代码 Intent.setType("image/jpg"); 代替 Intent.setType("image/*");

0

使用 setType 设置为 jpeg

intent.setType("image/jpeg")intent.setType("image/jpg")

或者设置为 png

intent.setType("image/png")


1
但是,我该如何允许其他的JPG和PNG格式?只允许这两种格式,不允许其他任何格式? - Ash
但是当我尝试这个时,即使我将其设置为intent.setType("image/jpg"),它仍然允许选择其他格式。 - Ash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接