在Xamarin中使用C#对字节数组进行映像

在Xamarin中使用C#对字节数组进行映像,c#,xamarin,xamarin.android,C#,Xamarin,Xamarin.android,在过去的几天里,我一直在寻找,但没有找到解决问题的方法。我目前正在开发xamarin Android应用程序。我想使用by数据库中的byte array列显示图像。我正在使用另一个程序查找特定照片的字节数组,然后手动将其值插入我的主要项目的字节数组列中 这是我试图复制图像的代码: Android.Graphics.Bitmap bitmap=BitmapFactory.DecodeByteArray(currentexercis.image, 0, currentexercis.image.Le

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

这是我试图复制图像的代码:

Android.Graphics.Bitmap bitmap=BitmapFactory.DecodeByteArray(currentexercis.image, 0, currentexercis.image.Length);
viewHolder.exercis_photo.SetImageBitmap(bitmap);
Currentexercis.image表示数据库中的字节数组,其值似乎正常,但每次位图都为null

这是我的另一个程序中的代码,我将图像转换为bytearray:

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");

我想你应该这样用

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
在Xamarin中使用C#对字节数组进行映像

有一些第三方库很好地实现了这一特性,比如or

对于
Glide
,有一个官方文档展示了如何在
Xamarin.Android
项目中使用它。 或者您可以直接从nuget软件包中使用它:

然后您可以这样编写示例代码:

Glide.With(context)
     .Load(imageBytes)
     .Apply(RequestOptions.CircleCropTransform())
     .Into(imageView);
转换成字节数组

 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));
   }
}
private void OnGetMemberAvatarCompleted(字节[]虚拟字节)
{
var avatarImageView=findviewbyd(Resource.Id.memberProfile\u avatar);
如果(avatarImageView!=null)
{
var imageBitmap=BitmapFactory.DecodeByteArray(avatarBytes,0,avatarBytes.Length);
RunOnUiThread(()=>avatarImageView.SetImageBitmap(imageBitmap));
}
}

在Java API中,
decodeByteArray
如果图像无法解码,则返回
null
。我假设在Xamarin库中也会发生同样的事情。谢谢,Ted,但是因为我从另一个程序中获得了字节数组,所以应该可以毫无问题地将其转换回图像。这只是一个相反的过程。也许你需要使用四参数版本的
DecodeByteArray
,并传入告诉工厂如何解码你的特定图像的选项。我刚刚在该辅助程序中添加了一个新按钮,以查看字节数组是否可用于解码,并且图像似乎已创建,但是我在那个程序中使用了内存流,在android程序中我不能使用内存流,因为我的图像是android类型。Widget image view和使用memorystream创建的图像是System Drawing Core image类型…嗨,谢谢你的回复。然而,当我试图完成关于位图创建的最后一行时,我需要在System Drawing Core和Android Graphics之间进行选择。我必须使用Android图形,而且它似乎没有位图的构造函数…下面的文章链接,我想你会找到如何使用位图。