![](/img/trans.png)
[英]Getting the bytes[] / stream of an Image or ImageSource in Xamarin.Forms?
[英]Xamarin Forms Image to Stream
我的目標是獲取一個嵌入的圖像,該圖像保存在每個項目的圖像文件夾中,進行流處理,將其轉換為字節數組,然后使用PCLStorage將其保存到設備的本地存儲文件系統中。 我不知道的部分是如何從嵌入的圖像中流式傳輸。
var embeddedImage = new Image { Aspect = Aspect.AspectFit };
embeddedImage.Source = ImageSource.FromResource("applicationIcon.png");
那么如果有路徑,就可以流式傳輸;如果有流,則可以將其轉換為byte []
。 下面的代碼不起作用,因為(顯然)找不到文件源。
string localFileUri = string.Empty;
// Get hold of the file system.
IFolder localFolder = FileSystem.Current.LocalStorage;
IFile file = await FileSystem.Current.GetFileFromPathAsync("applicationIcon.png");
using (Stream stream = await file.OpenAsync(FileAccess.Read))
{
using (var ms = new MemoryStream())
{
var byteArray = ms.ToArray();
var storeragePath = await iStorageService.SaveBinaryObjectToStorageAsync(string.Format(FileNames.ApplicationIcon, app.ApplicationId), byteArray);
app.IconURLLocal = storeragePath;
}
}
唯一的選擇似乎是使用某種資源定位器,然后為您添加的每種類型的項目維護該代碼。 不太優雅。 還有另一種方法嗎?
首先,感謝deckertron_9000為我提供了解決之道,其次是以下兩個鏈接:
Xamarin Forms:如何在PCL Project中使用嵌入式資源獲取圖像
最后,這對我有用:
首先,我將圖像添加到PCL中的文件夾中。 然后,確保將映像的“生成操作”更改為“嵌入式資源”。
其次,我使用System.Reflection添加;
第三,這段代碼對我有用:
string imagePath = "NameOfProject.Assets.applicationIcon.png";
Assembly assembly = typeof(NameOfClass).GetTypeInfo().Assembly;
byte[] buffer;
using (Stream stream = assembly.GetManifestResourceStream(imagePath))
{
long length = stream.Length;
buffer = new byte[length];
stream.Read(buffer, 0, (int)length);
var storeragePath = await iStorageService.SaveBinaryObjectToStorageAsync(string.Format(FileNames.ApplicationIcon, app.ApplicationId), buffer);
app.IconURLLocal = storeragePath;
}
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await App.CurrentApp.MainPage.DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg"
});
if (_mediaFile == null)
return;
//ViewModel.StoreImageUrl(file.Path);
await App.CurrentApp.MainPage.DisplayAlert("Snap", "Your photo have been added to your Items collection.", "OK");
ImageSource = ImageSource.FromStream(() =>
{
var stream = _mediaFile.GetStream();
_mediaFile.Dispose();
return stream;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.