Подтвердить что ты не робот

Как преобразовать файл в 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 [], получившей эту ошибку. Метод encodeBase64 (byte []) равен undefined для типа Base64

4b9b3361

Ответ 1

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

Но вы можете напрямую преобразовать его в String. Надеюсь, это сработает для вас.

Ответ 2

ОБНОВЛЕНИЕ: см. Комментарии об ошибке с этим ответом, который я изучаю

Обновленная, более эффективная версия 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()
            }
        }
    }
}

Ответ 3

Я считаю, что эти 2 примера кода помогут хотя бы кому-то так же, как многие из них помогли мне через эту платформу. Благодаря 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;
    }

Я буду рад ответить на любой вопрос, касающийся этих кодов.

Ответ 4

Чтобы преобразовать файл в 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);
}

Ответ 5

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

Ответ 6

Вы можете попробовать это.

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