如何在xamarin.android中将图像转换为base64? [英] how to convert an image into base64 in xamarin.android?

查看:217
本文介绍了如何在xamarin.android中将图像转换为base64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this code, it works very well in android studio but not in xamarin bitmap.Compress() has different arguments in xamarin and i am confused how to convert image into base64 or binary in xamarin.android?

我在第三行看到一个错误:

I am receving an error in the 3rd line:

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

( bitmap.Compress() has some invalid arguments).

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

推荐答案

如果您查看

If you look at the documentation for Bitmap.Compress in Xamarin, you'll see that the last parameter is a Stream.

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

The equivalent of ByteArrayOutputStream in .NET is MemoryStream, so your code would be:

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.)

(You could use Convert.ToBase64String instead of Base64.EncodeToString if you wanted, too.)

这篇关于如何在xamarin.android中将图像转换为base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆