[英]How to Set image upload to only jpg and png Files?
這是我正在使用的代碼,它工作得很好但是我如何只將文件類型設置為 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);
}
}
我認為所有給出的答案都是錯誤的。 要求是允許 jpg 和 png 文件。 這僅允許選擇給定的文件類型。
首先創建 mimeTypes 數組,包括所有允許的文件類型。
然后將其放入 Intent 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);
使用這個Intent.setType("image/jpg");
而不是Intent.setType("image/*");
對 jpeg 使用 setType
intent.setType("image/jpeg")
或intent.setType("image/jpg")
或 png
intent.setType("image/png")
我知道我回答晚了,但我只想分享對我有用的解決方案。
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
嘗試一下並告訴我它是否適用於您的用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.