163

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.

0

18 Answers 18

369

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

Sign up to request clarification or add additional context in comments.

17 Comments

ok, and them i can put that String (encondedImage) into a remote database column with PHP+JSON ???? wich type haves to be the column of the database? VARCHAR?
Well, with VARCHAR you need to specify how big it'd be, so maybe TEXT would be better. Image could be any range of sizes...
For me was working after replacing: String encodedImage = Base64.encode(byteArrayImage, Base64.DEFAULT); By: String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
Does anybody realize that this method makes a meaningless recompress of the file?? why is this so upvoted?? Chandra Sekhar's answer is the most efficient.
ElYeante - you're absolutely right, that's a more efficient way of doing it.
|
112

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

8 Comments

Of course this is more efficient; just transforms a file into its base64 representation, and avoids an absolutely meaningless recompression of the image.
is the fileName here the path of the file or the actual file name ??? Please don't forget to tag me :) Thanks.
@user2247689 When you are trying to access a file obviously you have to give the complete path of the file including its name. If the file is present in the same path where your source program is present, then file name is enough.
A question, what does '8192' signifies here, is it file size or what?
this code is not working, wasted many hours of mine to addess the issue.
|
8

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.

1 Comment

too hard for me, my skills are very low with this, i checked it on google and can't find easy examples... maybe if you can give me code examples like xil3 i will understand it
8

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

1 Comment

Shouldn't you close any opened inputstreams?
6
// 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; } 

Comments

4

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) { } } 

1 Comment

(will allocate a large string and can cause an OOM crash) So What is the solution in this case ?
3

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

Comments

2

Another way of writing in Kotlin, simpler:

fun imageBase64(filepath: String): String { FileInputStream(filepath).use { val bytes = it.readBytes() return Base64.encodeToString(bytes, Base64.DEFAULT) } } 

Comments

1

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

Comments

1

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

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!

Comments

1

Kotlin version:

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

Comments

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

2 Comments

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
An explanation would be in order.
0

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

Comments

0

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(); 

1 Comment

Will this actually compile? Did you leave something out?
0

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!

2 Comments

it is adding next line to the string, can we overcome this?
getting java.io.FileNotFoundException: /storage/emulated/0/1417462683.jpg (No such file or directory) even if file path is correct
0

In Kotlin You can just use decode function for byteArray...

 private fun stringToBitmap(encodedString: String): Bitmap { val imageBytes = decode(encodedString, DEFAULT) return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) } 

Comments

0

for encode

 private String encodeImage(Bitmap bitmap){ int previewWidth=150; int previewHeight=bitmap.getHeight()*previewWidth/ bitmap.getWidth(); Bitmap previewBitmap = Bitmap.createScaledBitmap(bitmap,previewWidth,previewHeight,false); ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); previewBitmap.compress(Bitmap.CompressFormat.JPEG,50,byteArrayOutputStream); byte[] bytes=byteArrayOutputStream.toByteArray(); return Base64.encodeToString(bytes,Base64.DEFAULT); } private final ActivityResultLauncher<Intent> pickImage=registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode()==RESULT_OK){ if (result.getData()!=null){ Uri imageuri=result.getData().getData(); try{ InputStream inputStream= getContentResolver().openInputStream(imageuri); Bitmap bitmap= BitmapFactory.decodeStream(inputStream); binding.imageProfile.setImageBitmap(bitmap); encodedImage= encodeImage(bitmap); }catch (FileNotFoundException e){ e.printStackTrace(); } } } } ); 

Comments

-2

Use this code:

byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

1 Comment

This is just the opposite

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.