将图片(最大200kb)转换为Base64字符串的代码是什么?
我需要知道如何在Android中做到这一点,因为我必须在我的主应用程序中添加上传图像到远程服务器的功能,将它们作为字符串放入数据库的一行中。
我在Google和Stack Overflow中搜索,但我找不到我能负担得起的简单示例,我也找到了一些示例,但它们不是关于转换为字符串的。然后,我需要转换成一个字符串,以便通过JSON上传到我的远程服务器。
发布于 2013-07-26 14:25:02
除了使用Bitmap
,您还可以通过一个简单的InputStream
来实现这一点。嗯,我不确定,但我认为它有点效率。
InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O API
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();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
发布于 2011-01-29 03:43:18
发布于 2017-02-08 14:52:10
// Put the image file path into this method
public static String getFileToByte(String filePath){
Bitmap bmp = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try{
bmp = BitmapFactory.decodeFile(filePath);
bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
}
catch (Exception e){
e.printStackTrace();
}
return encodeString;
}
https://stackoverflow.com/questions/4830711
复制相似问题