Android: Encode & Decode base64

前端 未结 2 2007
花落未央
花落未央 2021-01-17 03:54

How to encode and decode any image from base64 format.

I donno anything about base64, just now I came to know that it saves image in String format. Please explain ab

2条回答
  •  再見小時候
    2021-01-17 04:39

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

    Decode:

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

提交回复
热议问题