如何将文件转换为Base64?

时间:2015-02-27 05:17:28

标签: android base64

此处报告包含路径(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 [])是未定义的

7 个答案:

答案 0 :(得分:8)

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

但你可以直接将它转换为String。希望这对你有用。

答案 1 :(得分:6)

更新:查看有关我正在寻找的答案的错误的注释

Kotlin是一种更新的,更有效的版本,它绕过了位图,并且不将整个ByteArray存储在内存中(存在OOM错误)。

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

答案 2 :(得分:3)

我相信这两个示例代码将帮助至少有人通过这个平台帮助我的方式。感谢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 :(得分:1)

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

答案 4 :(得分:1)

 //Convert Any file, image or video or txt  into base64

 1.Import the below Dependancy
 compile 'commons-io:commons-io:2.4'

 2.Use below Code to convert file to 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);
        }

答案 5 :(得分:0)

你可以试试这个。

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

答案 6 :(得分:0)

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

并以这种方式调用

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