[英]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.