如何将图像转换为Base64字符串? [英] How can I convert an image into a Base64 string?

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

问题描述

将图像(最大200KB)转换为Base64字符串的代码是什么?

What is the code to transform an image (maximum of 200 KB) into a Base64 String?

我需要知道如何在Android上使用它,因为我必须添加将图像上传到主应用程序中的远程服务器的功能,并将其作为字符串放入数据库的行中.

I need to know how to do it with Android, because I have to add the functionality to upload images to a remote server in my main app, putting them into a row of the database, as a string.

我正在Google和Stack Overflow中进行搜索,但是我找不到可以负担得起的简单示例,也找到了一些示例,但是它们并不是在讨论如何转换为String.然后,我需要转换为字符串以通过JSON上传到我的远程服务器.

I am searching in Google and in Stack Overflow, but I could not find easy examples that I can afford and also I find some examples, but they are not talking about to transform into a String. Then I need to transform into a string to upload by JSON to my remote server.

推荐答案

您可以使用Base64 Android类:

You can use the Base64 Android class:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

尽管如此,您必须将图像转换为字节数组.这是一个示例:

You'll have to convert your image into a byte array though. Here's an example:

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();

*更新*

如果您使用的是较旧的SDK库(因为您希望它在具有旧版OS的手机上运行),则不会打包Base64类(因为它只是在API级别8 AKA版本中发布的) 2.2).

If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 AKA version 2.2).

查看本文以获取解决方法:

Check this article out for a workaround:

如何对base64进行编码解码Android

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

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