简体   繁体   English

将 Xamarin.Forms.Image 转换为字节数组

[英]Convert Xamarin.Forms.Image to Byte Array

Simple Question: I have a Xamarin.Forms.Image called "image".简单问题:我有一个名为“image”的 Xamarin.Forms.Image。 I need it to be a byte array.我需要它是一个字节数组。 I feel like this has to be a simple thing but I can't find it on the internet anywhere.我觉得这必须是一件简单的事情,但我无法在互联网上的任何地方找到它。

var image = Xamarin.Forms.Image();
image.source = "my_image_source.png";

//Magic code

byte[] imgByteArray = ???

Unfortunately, the Image class does not expose methods to access the actual image once loaded.不幸的是, Image class 不公开加载后访问实际图像的方法。

You will need to read the Image from the file and convert it to the Stream you are expecting.您需要从文件中读取图像并将其转换为您期望的 Stream。

To prevent reading the image object twice you can set the stream read to your Image control.为了防止读取图像 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.
}

Hope this helps.-希望这可以帮助。-

Update:更新:

This code will require adding your my_image_source.png as part of the PCL as an embedded resource.此代码将需要将您的my_image_source.png作为 PCL 的一部分添加为嵌入式资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM