【问题标题】:Android: Encode & Decode base64Android:编码和解码 base64
【发布时间】:2014-09-05 18:36:22
【问题描述】:

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

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

提前谢谢...

【问题讨论】:

标签: android image base64


【解决方案1】:

编码任何文件:

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);

【讨论】:

  • 它只是将文件转换为其base64表示,并避免对图像进行绝对无意义的重新压缩。
  • 我使用了 Base64.NO_WRAP 而不是 Base64.DEFAULT,它提供了与 freeonlinetools24.com/base64-image 相同的输出,太棒了!
【解决方案2】:

Base64 允许您以 ASCII 格式表示二进制数据,您可以将其用于向端点发送/接收图像

要编码/解码检查这两种方法:

public static String getBase64(Bitmap bitmap)
{
    try{
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();

        return Base64.encodeToString(byteArray, Base64.NO_WRAP);
    }
    catch(Exception e)
    {
        return null;
    }
}

public static Bitmap getBitmap(String base64){
    byte[] decodedString = Base64.decode(base64, Base64.NO_WRAP);
    return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    相关资源
    最近更新 更多