如何转换成图像的Base64字符串? [英] How to convert a image into Base64 string?

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

问题描述

有人可以告诉我的code来转换图像(200KB最多的)成Base64的字符串?

Can someone tell me the code to transform a image (maximum of 200KB) into Base64 String?

我需要知道如何与And​​roid做到这一点,因为我要补充上传图片到远程服务器,在我的主要的应用程序将它们放入一行的数据库,作为一个字符串的功能。

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.

我搜索在谷歌和计算器,但我找不到简单的例子,我可以 负担得起,我也找到了一些例子,但他们不是在谈论转化为字符串。然后,我需要转换成字符串通过JSON上传到我的远程服务器。

I am searching in google and in StackOverflow 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 String. Then I need to transform into string to upload by JSON to my remote server.

推荐答案

您可以使用的Base64安卓类:

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库(因为你想让它与旧版本的操作系统的工作电话),你将不会有包装的(因为它刚出来的时候在API级别8又名版本的Base64类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 work-around:

<一个href="http://android$c$cmonkey.blogspot.com/2010/03/how-to-base64-en$c$c-de$c$c-android.html">http://android$c$cmonkey.blogspot.com/2010/03/how-to-base64-en$c$c-de$c$c-android.html

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

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