Android:编码和解码base64 [英] Android: Encode & Decode base64

查看:108
本文介绍了Android:编码和解码base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对base64格式的任何图像进行编码和解码.

How to encode and decode any image from base64 format.

我对base64一无所知,现在我才知道它以String格式保存图像.请解释一下base64以及如何在android编码中使用它. 会缩小图像的大小吗?

I donno anything about base64, just now I came to know that it saves image in String format. Please explain about base64 and how to use it in android coding. Will it reduce the size of an image?

预先感谢...

推荐答案

要对任何文件进行编码:

To encode any file:

private String encodeFileToBase64(String filePath)
{
    InputStream inputStream = new FileInputStream(filePath);//You can get an inputStream using any IO 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();
    return Base64.encodeToString(bytes, Base64.DEFAULT);
}

解码:

byte[] data = Base64.decode(base64, Base64.DEFAULT);

这篇关于Android:编码和解码base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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