简体   繁体   English

如何以xamarin形式获取位图的字节[]数据?

[英]How to get byte[] data of a bitmap in xamarin forms?

I want to read an image into a byte array.我想将图像读入字节数组。

using my xaml, I have a binding for my image:使用我的 xaml,我的图像有一个绑定:

    <Image x:Name="myImageView"
           Source="triangles.bmp"
           Aspect="AspectFit" 
           VerticalOptions="Center"
           HorizontalOptions="FillAndExpand"/>

I would like to have the data from myImageView into a byte array.我想将 myImageView 中的数据转换为字节数组。 What code can accomplish this on xamarin forms ?什么代码可以在 xamarin 表单上完成此操作

I have found solutions for the other way around (which i haven't tested yet), but I need this way (bound image->byte[], not byte[]->Image).我已经找到了相反的解决方案(我还没有测试过),但我需要这种方式(绑定图像->字节[],而不是字节[]->图像)。

My usage will be, for example, to apply a bluring convolution filter, or to find the max pixel value.例如,我的用法是应用模糊卷积过滤器,或找到最大像素值。

Thanks.谢谢。

Since you're using PCL, you can achieve this by using the interface I created below and registering it with Xamarin DependencyService.由于您使用的是 PCL,您可以通过使用我在下面创建的接口并将其注册到 Xamarin DependencyService 来实现此目的。

I provided methods to get bytes from an URIImageSource & FileImageSource我提供了从URIImageSourceFileImageSource获取字节的方法

In Your PCL Project在您的 PCL 项目中

private void ABCDEFGHIJKLMNOPQRSTUVWXYZ(){
    var link = new Uri("https://xamarin.com/content/images/pages/forms/example-app.png");
    var goNative = DependencyService.Get<IStackoverflow>();
    var bytes = goNative.GetImageBytes(link);   // Your Bytes As Requested
}

public interface IStackoverflow  // Create an interface to access platform specific
{
    byte[] GetImageBytes(string filepath);
    byte[] GetImageBytes(Uri uri);
}

In your native project make sure you inherit from the above interface.在您的本机项目中,请确保您从上述接口继承。

If you're not accessing it from your PCL project then,如果你不是从你的 PCL 项目访问它,那么,

imagePath = Resources.GetDrawable(Resource.Drawable.triangles.bmp);      
public byte[] GetImageBytes(string imagePath)
{
    var fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
    var buffer = new byte[fileStream.Length];
    fileStream.Read(buffer, 0, (int)fileStream.Length);
    fileStream.Close();
    return buffer;
}

public byte[] GetImageBytes(Uri uri)
{
    var myWebClient = new WebClient();
    return  myWebClient.DownloadData(uri);
}

If you're unfamiliar with Xamarin DependencyService, here is their documentation Xamarin DependencyService如果您不熟悉 Xamarin DependencyService,这里是他们的文档Xamarin DependencyService

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

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