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屬性,您可以為它設定不同的形狀以達到您想要的裁剪效果,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/549597.html
標籤:其他
