【问题标题】:How to get byte[] data of a bitmap in xamarin forms?如何以 xamarin 形式获取位图的字节 [] 数据?
【发布时间】:2017-03-31 07:31:38
【问题描述】:

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

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

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

我想将 myImageView 中的数据放入一个字节数组中。 什么代码可以在 xamarin 表单上完成此操作?

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

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

谢谢。

【问题讨论】:

  • 你可以把它从磁盘读入一个字节[]。但是 Image 控件没有提供任何机制来访问它的内部图像数据。
  • @Jason 好的,然后我会从磁盘读取它。如何才能做到这一点?我一直在寻找字面上的时间,但一无所获。请给一个代码sn-p
  • 您使用的是 PCL 还是共享项目?您的图像存储在哪里?它是应用程序包的一部分,还是相机图像等?
  • @Jason 我正在使用 PCL

标签: c# image-processing mobile xamarin xamarin.forms


【解决方案1】:

由于您使用的是 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

【讨论】:

  • 谢谢!这非常接近工作,但是当我尝试访问图像时,我从 android 部分得到了一个异常。我应该在 android 或 Xamaril 便携式表单中以不同的方式说明路径吗?在 Xamarin 表单中,“triangles.bmp”有效。在android中,它没有找到该文件。
  • 我假设此图像是您项目的一部分,因为如果您尝试仅从本机 android 项目访问它,则它适用于您的表单,则需要将完整的文件路径用作文件名,例如,如果图像在您的可绘制文件夹中,文件名应为 Resource.Drawable.triangles.bmp
  • 带点?不是斜线?这是为什么?另外,我在哪里可以找到有关此的官方文档?
  • Dots 因为 resource.drawable 是 android 类。文档..developer.android.com/guide/topics/resources/…
  • imagePath = Resources.GetDrawable(Resource.Drawable.triangles.bmp);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 2019-10-16
  • 2023-03-24
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多