Android 如何将文件转换为Base64?

Android 如何将文件转换为Base64?,android,base64,Android,Base64,此处报告包含路径(sdcard中的路径名为字符串格式) 在字节[]编码行中获取此错误。 类型Base64的方法encodeBase64(字节[])未定义 String value = Base64.encodeToString(bytes, Base64.DEFAULT); 但您可以直接将其转换为字符串。希望这对您有用。您可以试试 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ... byt

此处报告包含路径(sdcard中的路径名为字符串格式)

在字节[]编码行中获取此错误。 类型Base64的方法encodeBase64(字节[])未定义

String value = Base64.encodeToString(bytes, Base64.DEFAULT);
但您可以直接将其转换为字符串。希望这对您有用。

您可以试试

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
...
byte[] byteArray = byteArrayOutputStream.toByteArray();
base64Value = Base64.encodeToString(byteArray, Base64.DEFAULT);

我相信这两个示例代码将至少帮助一些人,就像许多人通过这个平台帮助我一样。多亏了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;
    }

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

要将文件转换为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);
}

将任何文件、图像、视频或文本转换为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.导入以下依赖项

 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);
}
File File=新文件(filePath)//文件路径
字节[]b=新字节[(int)file.length()];
试一试{
FileInputStream FileInputStream=新的FileInputStream(文件);
fileInputStream.read(b);
对于(int j=0;j0){
base64String=android.util.Base64.encodeToString(byteFileArray,android.util.Base64.NO_WRAP);
Log.i(“文件Base64字符串”,“图像解析==>”+Base64字符串);
}

一个更新的、更高效的Kotlin版本,它绕过位图,不将整个ByteArray存储在内存中(有可能出现OOM错误)

公共静态字符串uriToBase64(Uri、ContentResolver解析器、布尔缩略图){
字符串encodedBase64=“”;
试一试{
byte[]bytes=readBytes(uri、解析器、缩略图);
encodedBase64=Base64.encodeToString(字节,0);
}捕获(IOE1异常){
e1.printStackTrace();
}
返回编码dbase64;

}
您的问题是:在Android环境中,应该使用什么来代替“encodeBase64”?您尝试过encode()API吗?这段代码本质上是将文件读取为位图,然后无缘无故地再次压缩它。如果您的文件已经是JPEG或PNG,在我的示例中使用我的答案会更有效Base64OutputStream会截断最后几个字节,而flush()则没有帮助
Base64.encodeToString(outputStream.toByteArray(),Base64.DEFAULT)
工作正常。小心。它是截断它还是只是实现了与后端预期不同的填充?请看,这可能与填充有关,但它看起来像一个bug:结果比
Base64短5个字节。encodeToString()
生成并使用
Base64进行解码。decode()
比原始结果少1-2个字节。看见当Android在编码/解码后无法呈现一些JPG时,我注意到了这个问题。嗯,这似乎是一个bug。我将提出一个问题我不确定这是否是一个bug或是
Base64OutputStream
的故意行为,但这家伙有。我已经相应地更新了我的答案。
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()
    }
}