How can I convert an image into a Base64 string?

AndroidBase64

Android Problem Overview


What is the code to transform an image (maximum of 200 KB) into a Base64 String?

I need to know how to do it with Android, because I have to add the functionality to upload images to a remote server in my main app, putting them into a row of the database, as a string.

I am searching in Google and in Stack Overflow, but I could not find easy examples that I can afford and also I find some examples, but they are not talking about to transform into a String. Then I need to transform into a string to upload by JSON to my remote server.

Android Solutions


Solution 1 - Android

You can use the Base64 Android class:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

You'll have to convert your image into a byte array though. Here's an example:

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();

*** Update ***

If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 AKA version 2.2).

Check this article out for a workaround:

How to base64 encode decode Android

Solution 2 - Android

Instead of using Bitmap, you can also do this through a trivial InputStream. Well, I am not sure, but I think it's a bit efficient.

InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();

try {
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
    }
}
catch (IOException e) {
    e.printStackTrace();
}

bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

Solution 3 - Android

If you need Base64 over JSON, check out Jackson: it has explicit support for binary data read/write as Base64 at both the low level (JsonParser, JsonGenerator) and data-binding level. So you can just have POJOs with byte[] properties, and encoding/decoding is automatically handled.

And pretty efficiently too, should that matter.

Solution 4 - Android

// Put the image file path into this method
public static String getFileToByte(String filePath){
    Bitmap bmp = null;
    ByteArrayOutputStream bos = null;
    byte[] bt = null;
    String encodeString = null;
    try{
        bmp = BitmapFactory.decodeFile(filePath);
        bos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bt = bos.toByteArray();
        encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
    }
    catch (Exception e){
      e.printStackTrace();
    }
    return encodeString;
}

Solution 5 - Android

This code runs perfect in my project:

profile_image.buildDrawingCache();
Bitmap bmap = profile_image.getDrawingCache();
String encodedImageData = getEncoded64ImageStringFromBitmap(bmap);


public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    byte[] byteFormat = stream.toByteArray();

    // Get the Base64 string
    String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);

    return imgString;
}

Solution 6 - Android

If you're doing this on Android, here's a helper copied from the React Native codebase:

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;

// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
  try {
    InputStream is = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
    byte[] buffer = new byte[8192];
    int bytesRead;
    try {
      while ((bytesRead = is.read(buffer)) > -1) {
        b64os.write(buffer, 0, bytesRead);
      }
      return baos.toString();
    } catch (IOException e) {
      Log.e(TAG, "Cannot read file " + path, e);
      // Or throw if you prefer
      return "";
    } finally {
      closeQuietly(is);
      closeQuietly(b64os); // This also closes baos
    }
  } catch (FileNotFoundException e) {
    Log.e(TAG, "File not found " + path, e);
    // Or throw if you prefer
    return "";
  }
}

private static void closeQuietly(Closeable closeable) {
  try {
    closeable.close();
  } catch (IOException e) {
  }
}

Solution 7 - Android

Here is the encoding and decoding code in Kotlin:

 fun encode(imageUri: Uri): String {
    val input = activity.getContentResolver().openInputStream(imageUri)
    val image = BitmapFactory.decodeStream(input , null, null)

    // Encode image to base64 string
    val baos = ByteArrayOutputStream()
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
    var imageBytes = baos.toByteArray()
    val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
    return imageString
}

fun decode(imageString: String) {

    // Decode base64 string to image
    val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
    val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

    imageview.setImageBitmap(decodedImage)
}

Solution 8 - Android

Convert an image to Base64 string in Android:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

Solution 9 - Android

For those looking for an efficient method to convert an image file to a Base64 string without compression or converting the file to a bitmap first, you can instead [encode the file as base64][1]

val base64EncodedImage = FileInputStream(imageItem.localSrc).use {inputStream - >
    ByteArrayOutputStream().use {outputStream - >
            Base64OutputStream(outputStream, Base64.DEFAULT).use {
                base64FilterStream - >
                    inputStream.copyTo(base64FilterStream)
                base64FilterStream.flush()
                outputStream.toString()
            }
      }
}

Hope this helps! [1]: https://stackoverflow.com/questions/28758014/how-to-convert-a-file-to-base64

Solution 10 - Android

Kotlin version:

fun File.toBase64(): String? {
 val result: String?
 inputStream().use { inputStream ->
    val sourceBytes = inputStream.readBytes()
    result = Base64.encodeToString(sourceBytes, Base64.DEFAULT)
 }

 return result
}

Solution 11 - Android

byte[] decodedString = Base64.decode(result.getBytes(), Base64.DEFAULT);

Solution 12 - Android

Below is the pseudocode that may help you:

public  String getBase64FromFile(String path)
{
    Bitmap bmp = null;
    ByteArrayOutputStream baos = null;
    byte[] baat = null;
    String encodeString = null;
    try
    {
        bmp = BitmapFactory.decodeFile(path);
        baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        baat = baos.toByteArray();
        encodeString = Base64.encodeToString(baat, Base64.DEFAULT);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

   return encodeString;
}

Solution 13 - Android

Here is code for image encoding and image decoding.

In an XML file

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="yyuyuyuuyuyuyu"
    android:id="@+id/tv5"
/>

In a Java file:

TextView textView5;
Bitmap bitmap;

textView5 = (TextView) findViewById(R.id.tv5);

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);

new AsyncTask<Void, Void, String>() {
    @Override
    protected String doInBackground(Void... voids) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        byte[] byteFormat = stream.toByteArray();

        // Get the Base64 string
        String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);

        return imgString;
    }

    @Override
    protected void onPostExecute(String s) {
       textView5.setText(s);
    }
}.execute();

Solution 14 - Android

I make a static function. Its more efficient i think.

public static String file2Base64(String filePath) {
        FileInputStream fis = null;
        String base64String = "";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            fis = new FileInputStream(filePath);
            byte[] buffer = new byte[1024 * 100];
            int count = 0;
            while ((count = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, count);
            }
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        base64String = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
        return base64String;

    }

Simple and easier!

Solution 15 - Android

Use this code:

byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);

Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNullPointerExceptionView Question on Stackoverflow
Solution 1 - Androidxil3View Answer on Stackoverflow
Solution 2 - AndroidChandra SekharView Answer on Stackoverflow
Solution 3 - AndroidStaxManView Answer on Stackoverflow
Solution 4 - Androidkrishan kumar SharmaView Answer on Stackoverflow
Solution 5 - Androidtej shahView Answer on Stackoverflow
Solution 6 - AndroidMartin KonicekView Answer on Stackoverflow
Solution 7 - AndroidSamView Answer on Stackoverflow
Solution 8 - AndroidAftab AlamView Answer on Stackoverflow
Solution 9 - AndroidAlessi 42View Answer on Stackoverflow
Solution 10 - AndroidGustavo RossView Answer on Stackoverflow
Solution 11 - AndroidfdhchcView Answer on Stackoverflow
Solution 12 - AndroidvivekView Answer on Stackoverflow
Solution 13 - AndroidAsif AliView Answer on Stackoverflow
Solution 14 - AndroidIzzamedView Answer on Stackoverflow
Solution 15 - AndroidPJ2104View Answer on Stackoverflow