首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将图片转换为Base64字符串?

如何将图片转换为Base64字符串?
EN

Stack Overflow用户
提问于 2011-01-29 00:39:21
回答 13查看 260.6K关注 0票数 154

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

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

我在Google和Stack Overflow中搜索,但我找不到我能负担得起的简单示例,我也找到了一些示例,但它们不是关于转换为字符串的。然后,我需要转换成一个字符串,以便通过JSON上传到我的远程服务器。

EN

回答 13

Stack Overflow用户

发布于 2013-07-26 14:25:02

除了使用Bitmap,您还可以通过一个简单的InputStream来实现这一点。嗯,我不确定,但我认为它有点效率。

代码语言:javascript
复制
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);
票数 107
EN

Stack Overflow用户

发布于 2011-01-29 03:43:18

如果您需要Base64 over JSON,请查看Jackson:它在低级(JsonParser、JsonGenerator)和数据绑定级别都明确支持以Base64格式读/写二进制数据。因此,您可以只使用具有byte[]属性的POJOs,并自动处理编码/解码。

而且效率也很高,如果这很重要的话。

票数 8
EN

Stack Overflow用户

发布于 2017-02-08 14:52:10

代码语言:javascript
复制
// 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;
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4830711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档