使用 Java 将图片转换成 Base64 编码

本文主要是介绍使用 Java 将图片转换成 Base64 格式的编码。

public static String getBase64(File src) {
        String base64String = "";
        try (FileInputStream fis = new FileInputStream(src)) {

            byte[] buffer = new byte[(int) src.length()];
            int offset = 0;
            int numRead = 0;
            while (offset < buffer.length & (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) {
                offset += numRead;
            }

            if (offset != buffer.length) {
                throw new IOException("Could not completely read file "
                    + src.getName());
            }
            BASE64Encoder encoder = new BASE64Encoder();
            base64String = encoder.encode(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "data:image/jpeg;base64," + base64String;
    }