如何将图像转换为xamarin.android中的base64?

时间:2016-04-24 08:05:42

标签: c# image bitmap xamarin.android

我有这个代码,它在android studio中运行得很好但在xamarin中却不行 bitmap.Compress()在xamarin 中有不同的参数,我很困惑如何在xamarin.android中将图像转换为base64或二进制文件?

我在第3行收到错误:

  

(bitmap.Compress()有一些无效的参数。)

Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ace1);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100,bao);
byte[] ba = bao.ToByteArray();
string bal = Base64.EncodeToString(ba, Base64.Default);

2 个答案:

答案 0 :(得分:2)

如果您查看Xamarin中的documentation for Bitmap.Compress,您会看到最后一个参数是Stream

.NET中ByteArrayOutputStream的等效值为MemoryStream,因此您的代码为:

Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ace1);
MemoryStream stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
byte[] ba = stream.ToArray();
string bal = Base64.EncodeToString(ba, Base64.Default);

(如果您愿意,也可以使用Convert.ToBase64String代替Base64.EncodeToString。)

答案 1 :(得分:0)

这就是我为Bitmap对象获取Byte[] imageArray = null; Bitmap selectedProfilePic = this.GetProfilePicBitmap (); if (selectedProfilePic != null) { using (var ms = new System.IO.MemoryStream ()) { selectedProfilePic.Compress (Bitmap.CompressFormat.Png, 0, ms); imageArray = ms.ToArray (); } } 的方式:

{{1}}

希望这有帮助。

相关问题