18

Here the report contain the path(pathname in sdcard in string format)

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

in the byte[] encoded line getting this error. The method encodeBase64(byte[]) is undefined for the type Base64

sandrstar
  • 11,931
  • 7
  • 58
  • 64
zyonneo
  • 1,111
  • 5
  • 15
  • 43
  • Is your question: what should be used instead of 'encodeBase64' in Android context? Have You tried http://developer.android.com/reference/android/util/Base64.html encode() APIs? – sandrstar Feb 27 '15 at 05:25

7 Answers7

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

But you can directly convert it in to String .Hope this will work for you.

Sajith Vijesekara
  • 1,222
  • 2
  • 15
  • 46
15

An updated, more efficient, Kotlin version, that bypasses Bitmaps and doesn't store entire ByteArray's in memory (risking OOM errors).

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()
    }
}
Carson Holzheimer
  • 2,309
  • 18
  • 33
  • In my case Base64OutputStream truncates last several bytes, and flush() does not help. `Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT)` works flawlessly. Be careful. – gmk57 Apr 18 '19 at 15:38
  • Is it truncating it or is it just implementing padding differently than your backend expects? See [wiki about padding](https://en.wikipedia.org/wiki/Base64) – Carson Holzheimer Apr 22 '19 at 23:54
  • Maybe it's related to padding, but it looks like a bug: result is up to 5 bytes shorter than `Base64.encodeToString()` produces and decoding back with `Base64.decode()` gives 1-2 bytes less than the original. See [this Gist](https://gist.github.com/gmk57/061f34cc6742c7ba16f89aa23feeaff1). I noticed this issue when Android couldn't render some JPGs after encoding/decoding. – gmk57 Apr 25 '19 at 08:46
  • 1
    Hmm seems like a bug. I'll raise an issue – Carson Holzheimer Apr 26 '19 at 05:28
  • 1
    I'm not sure if it's a bug or intentional behaviour of `Base64OutputStream`, but this guy has [the solution](https://stackoverflow.com/a/24903555/4672107). I've updated my answer accordingly. – Carson Holzheimer Aug 01 '19 at 07:20
  • It seems like a bug in Base64OutputStream, in that it doesn't flush it's internal buffer when `flush()` is callled, since it doesn't implement it, but it does implement `close()` – Carson Holzheimer Aug 01 '19 at 07:27
  • I used this one but my server is not able to decode that string – Ajit Kumar Dubey Jan 30 '20 at 09:52
  • Can you be more specific? Have you tried other methods and compared the string? – Carson Holzheimer Jan 30 '20 at 09:55
5

I believe these 2 sample codes will help at least someone the same way many have helped me through this platform. Thanks to 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;
    }

I will be glad to answer any question regarding to these codes.

Edwinfad
  • 447
  • 5
  • 13
2

To convert a file to 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);
}
instanceof
  • 977
  • 17
  • 28
  • This code essentially reads the file to Bitmap, then compresses it again for no reason. If your file is already JPEG or PNG, it's more efficient to use my answer https://stackoverflow.com/a/54532684/4672107 – Carson Holzheimer Feb 05 '19 at 10:54
1

Convert Any file, image or video or text 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);
}
Adil Soomro
  • 36,617
  • 9
  • 98
  • 146
Ramesh sambu
  • 3,285
  • 1
  • 21
  • 37
0

You can try this.

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
...
byte[] byteArray = byteArrayOutputStream.toByteArray();
base64Value = Base64.encodeToString(byteArray, Base64.DEFAULT);
eckes
  • 9,350
  • 1
  • 52
  • 65
vishalk
  • 519
  • 3
  • 12
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;
    }

and call it in this way

   String image = BitmapUtils.uriToBase64(Uri.fromFile(file), context.getContentResolver());
Farido mastr
  • 353
  • 3
  • 10