How can I convert an image into a Base64 string?

前端 未结 14 1339
离开以前
离开以前 2020-11-22 06:52

What is the code to transform an image (maximum of 200 KB) into a Base64 String?

I need to know how to do it with Android, because I have to add the functionali

14条回答
  •  迷失自我
    2020-11-22 07:17

    I make a static function. Its more efficient i think.

    public static String file2Base64(String filePath) {
            FileInputStream fis = null;
            String base64String = "";
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                fis = new FileInputStream(filePath);
                byte[] buffer = new byte[1024 * 100];
                int count = 0;
                while ((count = fis.read(buffer)) != -1) {
                    bos.write(buffer, 0, count);
                }
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            base64String = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
            return base64String;
    
        }
    

    Simple and easier!

提交回复
热议问题