有人能告诉我将图像(最大200KB)转换为Base64字符串的代码吗?
我需要知道如何使用android,因为我必须添加上传图像的功能到我的主应用程序中的远程服务器,将它们作为字符串放入数据库的一行.
我在谷歌和StackOverflow中搜索,但我找不到我能负担得起的简单示例,而且我找到了一些例子,但他们并没有谈到转换成字符串.然后我需要转换为字符串以通过JSON上传到我的远程服务器.
我试图将文件从SD卡转换为Base64,但似乎文件太大,我得到一个OutOfMemoryError.
这是我的代码:
InputStream inputStream = null;//You can get an inputStream using any IO API
inputStream = new FileInputStream(file.getAbsolutePath());
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
attachedFile = Base64.encodeToString(bytes, Base64.DEFAULT);
Run Code Online (Sandbox Code Playgroud)
有没有办法在归档String attachedFile时绕过OutOfMemoryError?
我正在写信要求解决以下困难的正确解决方案:
我需要以Base64格式对文件进行编码,并且我无法使文件变小,因此,我肯定会遇到OutOfMemory Exception,这就是为什么我使用Streaming方法来解决它.文件编码后,我已经通过代码和在线工具立即对其进行了解码.发现解码后的内容有时在文件末尾缺少2个字节,但并非总是如此.它确实影响了对文件的进一步处理.
希望有人可以提供帮助,可能是由于白痴的错误造成的.还是谢谢.
这是代码:
FileOutputStream fout = new FileOutputStream(path + ".txt");
//this is for printing out the base64 content
FileInputStream fin = new FileInputStream(path);
System.out.println("File Size:" + path.getTotalSpace());
ByteArrayOutputStream os = new ByteArrayOutputStream();
Base64OutputStream base64out = new Base64OutputStream(os,Base64.NO_WRAP);
byte[] buffer = new byte[3 * 512];
int len = 0;
while ((len = fin.read(buffer)) >= 0) {
base64out.write(buffer, 0, len);
}
System.out.println("Encoded Size:" + os.size());
String result = new String(os.toByteArray(), "UTF-8");
fout.write(os.toByteArray());
fout.close();
base64out.close();
os.close();
fin.close();
return result;
Run Code Online (Sandbox Code Playgroud) 如何将SD卡文件(.pdf,.txt)转换为基本64字符串和字符串发送到服务器