What is the code to transform an image (maximum of 200 KB) into a Base64 String?
我需要知道如何使用安卓系统,因为我必须在我的主应用程序中添加将图像上传到远程服务器的功能,将它们作为字符串放入数据库的一行.
我在Google和Stack Overflow中搜索,但我找不到我负担得起的简单示例,我也找到了一些示例,但它们不是在谈论如何转换为字符串.然后,我需要转换为字符串,以便通过JSON上传到我的远程服务器.
What is the code to transform an image (maximum of 200 KB) into a Base64 String?
我需要知道如何使用安卓系统,因为我必须在我的主应用程序中添加将图像上传到远程服务器的功能,将它们作为字符串放入数据库的一行.
我在Google和Stack Overflow中搜索,但我找不到我负担得起的简单示例,我也找到了一些示例,但它们不是在谈论如何转换为字符串.然后,我需要转换为字符串,以便通过JSON上传到我的远程服务器.
您可以使用Base64 Android类:
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
不过,您必须将图像转换为字节array.下面是一个示例:
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();
* Update *个
如果您使用的是较旧的SDK库(因为您希望它能在具有较旧版本操作系统的手机上工作),那么就不会打包Base64类(因为它刚刚在API级别8即版本2.2中发布).
请查看本文,了解解决方法:
100