【问题标题】:Byte Array to Image using C# in Xamarin在 Xamarin 中使用 C# 将字节数组转换为图像
【发布时间】:2018-09-18 03:54:50
【问题描述】:

过去几天我一直在寻找,但没有找到解决问题的方法。我目前正在开发一个 xamarin Android 应用程序。我想通过使用数据库中的字节数组列来显示图像。我正在使用另一个程序来查找特定照片的字节数组,然后我将其值手动插入到我的主要项目的字节数组列中。

这是我试图重现图像的代码:

Android.Graphics.Bitmap bitmap=BitmapFactory.DecodeByteArray(currentexercis.image, 0, currentexercis.image.Length);
viewHolder.exercis_photo.SetImageBitmap(bitmap);

Currentexercis.image 代表我数据库中的字节数组,它的值似乎还可以,但是每次位图都是空的。

这是我将图像转换为字节数组的其他程序的代码:

Image img = Image.FromFile(opendlg.FileName);
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
dbpicEntities1 db = new dbpicEntities1();
db.MyPictures.Add(new MyPicture() { FileName=fileName, Data = ms.ToArray() });
db.SaveChanges();
MessageBox.Show("success");

【问题讨论】:

  • 在 Java API 中,如果图像无法解码,decodeByteArray 将返回 null。我假设 Xamarin 库中也会发生同样的事情。
  • 谢谢,Ted,但由于我从另一个程序中获取字节数组,它应该可以毫无问题地转换回图像。这只是相反的过程。
  • 也许您需要使用DecodeByteArray 的四参数版本并传入选项,告诉工厂如何解码您的特定图像。
  • 我刚刚向该辅助程序添加了一个新按钮,以查看字节数组是否可用于解码并且图像似乎已创建,但我在该程序中使用内存流并且在 android 程序中,我不能使用内存流,因为我的图像是 Android.Widget Image view 类型,而使用 memorystream 创建的图像是 System Drawing Core Image...

标签: c# xamarin xamarin.android


【解决方案1】:

转换为字节数组

 byte[] imgdata = System.IO.File.ReadAllBytes(pathToImage);

将字节数组转换为位图

 private void OnGetMemberAvatarCompleted(byte[] avatarBytes)
{
   var avatarImageView = FindViewById<ImageView>(Resource.Id.memberProfile_avatar);
   if (avatarImageView != null)
   {
      var imageBitmap = BitmapFactory.DecodeByteArray(avatarBytes, 0,avatarBytes.Length);
      RunOnUiThread(() => avatarImageView.SetImageBitmap(imageBitmap));
   }
}

【讨论】:

    【解决方案2】:

    在 Xamarin 中使用 C# 将字节数组转换为图像

    有一些第三方库很好地实现了这个功能,比如PicassoGlide

    对于Glide,在Xamarin.Android项目中有官方文档说明如何使用它:Binding a .JAR。 或者您可以直接从 nuget 包中使用它:

    然后你可以像这样编写代码:

    Glide.With(context)
         .Load(imageBytes)
         .Apply(RequestOptions.CircleCropTransform())
         .Into(imageView);
    

    【讨论】:

      【解决方案3】:

      我认为你应该这样使用。

      byte [] imageArray // is your data
      MemoryStream mStream = new MemorySteram ();
      mStream.write(imageArray,0,imageArray.Length);
      Image img = Image.FromStream(mStream);
      img.save(filelocation);
      
      Bitmap bitmapimg = BitmapFactory.BitmapFactory.DecodeStream(mStream); 
      // if you want to use Bitmap
      

      【讨论】:

      • 您好,感谢您的回复。但是,当我尝试完成有关位图创建的最后一行时,我需要在 System Drawing Core 和 Android Graphics 之间进行选择。我必须使用Android Graphics,它似乎没有Bitmap的构造函数......
      • 下面的文章链接,我想你会发现如何使用位图。link
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多