How can I convert an image into a Base64 string?

前端 未结 14 1348
离开以前
离开以前 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:03

    Instead of using Bitmap, you can also do this through a trivial InputStream. Well, I am not sure, but I think it's a bit efficient.

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

提交回复
热议问题