How can I convert an image into a Base64 string?

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

    If you're doing this on Android, here's a helper copied from the React Native codebase:

    import java.io.ByteArrayOutputStream;
    import java.io.Closeable;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    
    import android.util.Base64;
    import android.util.Base64OutputStream;
    import android.util.Log;
    
    // You probably don't want to do this with large files
    // (will allocate a large string and can cause an OOM crash).
    private String readFileAsBase64String(String path) {
      try {
        InputStream is = new FileInputStream(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
        byte[] buffer = new byte[8192];
        int bytesRead;
        try {
          while ((bytesRead = is.read(buffer)) > -1) {
            b64os.write(buffer, 0, bytesRead);
          }
          return baos.toString();
        } catch (IOException e) {
          Log.e(TAG, "Cannot read file " + path, e);
          // Or throw if you prefer
          return "";
        } finally {
          closeQuietly(is);
          closeQuietly(b64os); // This also closes baos
        }
      } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found " + path, e);
        // Or throw if you prefer
        return "";
      }
    }
    
    private static void closeQuietly(Closeable closeable) {
      try {
        closeable.close();
      } catch (IOException e) {
      }
    }
    

提交回复
热议问题