[英]Convert Xamarin.Forms.Image to Byte Array
簡單問題:我有一個名為“image”的 Xamarin.Forms.Image。 我需要它是一個字節數組。 我覺得這必須是一件簡單的事情,但我無法在互聯網上的任何地方找到它。
var image = Xamarin.Forms.Image();
image.source = "my_image_source.png";
//Magic code
byte[] imgByteArray = ???
不幸的是, Image
class 不公開加載后訪問實際圖像的方法。
您需要從文件中讀取圖像並將其轉換為您期望的 Stream。
為了防止讀取圖像 object 兩次,您可以將 stream 讀取設置為Image
控件。
var image = Xamarin.Forms.Image();
var assembly = this.GetType().GetTypeInfo().Assembly;
byte[] imgByteArray = null;
using (var s = assembly.GetManifestResourceStream("my_image_source.png"))
{
if (s != null)
{
var length = s.Length;
imgByteArray = new byte[length];
s.Read(buffer, 0, (int)length);
image.Source = ImageSource.FromStream(() => s);
}
}
// here imageByteArray will have the bytes from the image file or it will be null if the file was not loaded.
if (imgByteArray != null)
{
//use your data here.
}
希望這可以幫助。-
更新:
此代碼將需要將您的my_image_source.png
作為 PCL 的一部分添加為嵌入式資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.