如何将文件转换为Base64?

23

这里的报告包含路径(以字符串格式表示的sdcard路径名)

File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, report);
String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile);

private static String encodeFileToBase64Binary(File fileName) throws IOException {
    byte[] bytes = loadFile(fileName);
    byte[] encoded = Base64.encodeBase64(bytes);

    String encodedString = new String(encoded);
    return encodedString;
}

在获取byte[]编码行时出现了错误。 对于类型Base64,方法encodeBase64(byte[])未定义。


你的问题是:在Android环境中,应该使用什么代替'encodeBase64'?你尝试过http://developer.android.com/reference/android/util/Base64.html encode() API了吗? - sandrstar
7个回答

19

一个更新、更高效的 Kotlin 版本,绕过位图并且不将整个 ByteArray 存储在内存中(有避免 OOM 错误的风险)。

fun convertImageFileToBase64(imageFile: File): String {
    return ByteArrayOutputStream().use { outputStream ->
        Base64OutputStream(outputStream, Base64.DEFAULT).use { base64FilterStream ->
            imageFile.inputStream().use { inputStream ->
                inputStream.copyTo(base64FilterStream)
            }
        }
        return@use outputStream.toString()
    }
}

在我的情况下,Base64OutputStream 截断了最后几个字节,并且 flush() 也没有帮助。Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT) 可以完美地工作。请小心。 - gmk57
它是截断还是实现了与您的后端不同的填充方式?请参见关于填充的维基百科 - Carson Holzheimer
1
嗯,看起来像是个bug。我会提出一个问题。 - Carson Holzheimer
1
我不确定Base64OutputStream的行为是一个bug还是有意为之,但是这位大佬已经提供了解决方案。我已经相应地更新了我的答案。 - Carson Holzheimer
1
我使用了这个,但我的服务器无法解码那个字符串。 - Ajit Kumar Dubey
显示剩余3条评论

18
String value = Base64.encodeToString(bytes, Base64.DEFAULT);

但是你可以直接将它转换成字符串。希望这对你有用。


6

我相信这两个样例代码将至少帮助到某些人,就像许多人通过这个平台帮助了我一样。感谢StackOverflow。

// Converting Bitmap image to Base64.encode String type
    public String getStringImage(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
}
    // Converting File to Base64.encode String type using Method
    public String getStringFile(File f) {
        InputStream inputStream = null; 
        String encodedFile= "", lastVal;
        try {
            inputStream = new FileInputStream(f.getAbsolutePath());

        byte[] buffer = new byte[10240];//specify the size to allow
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                output64.write(buffer, 0, bytesRead);
            }
        output64.close();
        encodedFile =  output.toString();
        } 
         catch (FileNotFoundException e1 ) {
                e1.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        lastVal = encodedFile;
        return lastVal;
    }

我很乐意回答任何关于这些代码的问题。


3

将文件转换为Base64:

File imgFile = new File(filePath);
if (imgFile.exists() && imgFile.length() > 0) {
    Bitmap bm = BitmapFactory.decodeFile(filePath);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
    String base64Image = Base64.encodeToString(bOut.toByteArray(), Base64.DEFAULT);
}

这段代码基本上是将文件读取为位图,然后无缘无故地再次压缩它。如果您的文件已经是JPEG或PNG格式,使用我的答案 https://dev59.com/qF4b5IYBdhLWcg3wtjzY#54532684 更有效率。 - Carson Holzheimer

1
将任何文件、图像、视频或文本转换为base64
1. 导入以下依赖项
 compile 'commons-io:commons-io:2.4'

2.使用以下代码将文件转换为base64

File file = new File(filePath);  //file Path
byte[] b = new byte[(int) file.length()];
 try {
    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.read(b);
    for (int j = 0; j < b.length; j++) {
        System.out.print((char) b[j]);
    }
} catch (FileNotFoundException e) {
    System.out.println("File Not Found.");
    e.printStackTrace();
} catch (IOException e1) {
    System.out.println("Error Reading The File.");
    e1.printStackTrace();
}

byte[] byteFileArray = new byte[0];
 try {
    byteFileArray = FileUtils.readFileToByteArray(file);
} catch (IOException e) {
    e.printStackTrace();
}

String base64String = "";
 if (byteFileArray.length > 0) {
    base64String = android.util.Base64.encodeToString(byteFileArray, android.util.Base64.NO_WRAP);
    Log.i("File Base64 string", "IMAGE PARSE ==>" + base64String);
}

1

    public static String uriToBase64(Uri uri, ContentResolver resolver, boolean thumbnail) {
        String encodedBase64 = "";
        try {
            byte[] bytes = readBytes(uri, resolver, thumbnail);
            encodedBase64 = Base64.encodeToString(bytes, 0);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return encodedBase64;
    }

    private static byte[] readBytes(Uri uri, ContentResolver resolver, boolean thumbnail)
            throws IOException {
        // this dynamically extends to take the bytes you read
        InputStream inputStream = resolver.openInputStream(uri);
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

        if (!thumbnail) {
            // this is storage overwritten on each iteration with bytes
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];

            // we need to know how may bytes were read to write them to the
            // byteBuffer
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                byteBuffer.write(buffer, 0, len);
            }
        } else {
            Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
            int thumb_width = imageBitmap.getWidth() / 2;
            int thumb_height = imageBitmap.getHeight() / 2;
            if (thumb_width > THUMBNAIL_SIZE) {
                thumb_width = THUMBNAIL_SIZE;
            }
            if (thumb_width == THUMBNAIL_SIZE) {
                thumb_height = ((imageBitmap.getHeight() / 2) * THUMBNAIL_SIZE)
                        / (imageBitmap.getWidth() / 2);
            }
            imageBitmap = Bitmap.createScaledBitmap(imageBitmap, thumb_width, thumb_height, false);
            imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteBuffer);
        }
        // and then we can return your byte array.
        return byteBuffer.toByteArray();
    }

并以这种方式调用它

   String image = BitmapUtils.uriToBase64(Uri.fromFile(file), context.getContentResolver());


@UmutADALI 我已经更新了我的答案,你可以看到读取字节的函数。 - Farido mastr

0
你可以试试这个。
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
...
byte[] byteArray = byteArrayOutputStream.toByteArray();
base64Value = Base64.encodeToString(byteArray, Base64.DEFAULT);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接