MAUI 實現圖片上傳功能 1、Mainpage.xmal 中進行調用 代碼如下 <Image x:Name="Image_Upload" Source="{Binding User.HeaderImg}" /> <Button Text="上傳" Clicked="UploadImage_Clic ...
MAUI 實現圖片上傳功能
1、Mainpage.xmal 中進行調用 代碼如下
<Image x:Name="Image_Upload" Source="{Binding User.HeaderImg}" /> <Button Text="上傳" Clicked="UploadImage_Clicked"/>
2,創建一個UploadImage類 實現選擇圖片並上傳的方法
public class UploadImage { /// <summary> /// 選擇圖片 /// </summary> /// <returns></returns> public async Task<FileResult> OpenMediaPickerAsync() { try { var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions { Title = "請選擇圖片" }); if (result.ContentType == "image/png" || result.ContentType == "image/jpeg" || result.ContentType == "image/png") return result; else await App.Current.MainPage.DisplayAlert("圖片類型錯誤", "請選擇新的圖片", "確定"); return null; } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } } public async Task<Stream> FileResultToStream(FileResult fileResult) { if (fileResult == null) return null; return await fileResult.OpenReadAsync(); } public Stream ByteArrayToStream(byte[] bytes) { return new MemoryStream(bytes); } public string ByteBase64ToString(byte[] bytes) { return Convert.ToBase64String(bytes); } public byte[] StringToByteBase64(string text) { return Convert.FromBase64String(text); } public async Task<ImageFile> Upload(FileResult fileResult) { byte[] bytes; try { using (var ms=new MemoryStream()) { var stream = await FileResultToStream(fileResult); stream.CopyTo(ms); bytes=ms.ToArray(); } return new ImageFile { ByteBase64 = ByteBase64ToString(bytes), ContentType = fileResult.ContentType, FileName = fileResult.FileName }; } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } } }
’
3,在mainpage.xmal.cs中引用UploadImage 類實現 UploadImage_Clicked 方法
1 private async void UploadImage_Clicked(object sender, EventArgs e) 2 { 3 var img = await uploadimage.OpenMediaPickerAsync(); 4 var imagefile = await uploadimage.Upload(img); 5 6 Image_Upload.Source = ImageSource.FromStream(() => 7 8 uploadimage.ByteArrayToStream(uploadimage.StringToByteBase64(imagefile.ByteBase64)) 9 ); 10 11 }
如果需要進一步升級,比如 實現頭像上傳使用XAML 是否有辦法在.NET MAUI(適用於Android和iOS)中實現裁剪圖像的功能?
可以使用IImage.Resize
方法來調整圖像的大小。
Maui中的圖像有一個Clip屬性,您可以為它設置不同的形狀以達到您想要的裁剪效果。