繁体   English   中英

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

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

我想将图像读入字节数组。

使用我的 xaml,我的图像有一个绑定:

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

我想将 myImageView 中的数据转换为字节数组。 什么代码可以在 xamarin 表单上完成此操作

我已经找到了相反的解决方案(我还没有测试过),但我需要这种方式(绑定图像->字节[],而不是字节[]->图像)。

例如,我的用法是应用模糊卷积过滤器,或找到最大像素值。

谢谢。

由于您使用的是 PCL,您可以通过使用我在下面创建的接口并将其注册到 Xamarin DependencyService 来实现此目的。

我提供了从URIImageSourceFileImageSource获取字节的方法

在您的 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);
}

在您的本机项目中,请确保您从上述接口继承。

如果你不是从你的 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);
}

如果您不熟悉 Xamarin DependencyService,这里是他们的文档Xamarin DependencyService

暂无
暂无

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

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