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

查看:29
本文介绍了如何在 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);

推荐答案

如果你看一下 Xamarin 中 Bitmap.Compress 的文档,你会看到最后一个参数是一个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天全站免登陆