How to convert byte array to base64 String - java

List<Map<String, Object>> lists = baseDao.getJdbcTemplate().queryForList(queryForImages, productId);
**System.out.println("size----" + lists.size());**
ArrayList<String> arrayList = new ArrayList<String>();
for (Map<String, Object> base64 : lists) {
byte[] imgData = (byte[]) base64.get("images");
String base64Encoded = new String(imgData, StandardCharsets.UTF_8);
// byte[] encodedImage = Base64.encodeBase64(imgData);
System.out.println("encoded---2" + base64Encoded);
}
i retrieve list of images from db and convert byte array to base64 string ,if i sysout only the last image in the list prints in sysout , even sysout list.size under the method is not printing .

In android, you can use Base64 (android.util.Base64) to encoded byte[] to String;
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
and
Decoding part as like following;
byte[] byteArray = org.apache.commons.codec.binary.Base64.decodeBase64(encodedString);
Usually this technique used in android app to send binary file/data to Server, using Web Service;

To start with, this is wrong:
String base64Encoded = new String(imgData, StandardCharsets.UTF_8);
The image bytes you have do not represent UTF-8 encoded text, so it makes no sense to create a String out of the bytes, pretending that this is UTF-8 encoded text.
If you are using Java 8, then use the Base64 class available in the standard library:
import java.util.Base64;
// ...
byte[] imgData = (byte[]) base64.get("images");
String base64Encoded = Base64.getEncoder().encodeToString(imgData);
If you are not using Java 8, you can use a third-party library, for example Apache Commons Codec, which includes classes for Base64 encoding and decoding.

If you are working with Android you can use the following code by importing the Android version of the Base64 class:
Base64.encodeToString(payload, Base64.DEFAULT);
From Android API 26, you can use java.util.Base64 as well.

Prior to java 1.8 use apache commons library
String base64 = new String(Base64.encodeBase64(imgData))

Related

Java - encode a string to Base64

I am converting a piece of javascript code to java and want to encode a string to Base64 in java.
Code in javascript:
let encodedData = btoa(String.fromCharCode.apply(null, new Uint8Array(array)))
This converts Uint8Array to string first and then encode it to Base64. But I am not able to find a way to do same in java.
Java code is
InputStream insputStream = new FileInputStream(file);
long length = file.length();
byte[] bytes = new byte[(int) length];
insputStream.read(bytes);
insputStream.close();
byte[] encodedBytes = Base64.getEncoder().encode(bytes);
Which is encoding bytes. Dues to which, encodedData(js) and encodedBytes(java) are not same.
What I want to do is something like:
String str = new String(bytes);
byte[] encodedBytes = Base64.getEncoder().encode(str); // ERROR: encode doesn't accept string
Is there any way to achieve this?
Base64.getEncoder().encode(str.getBytes(Charset)) may help you
(as Thomas noticed). But i can't guess your charset. The right syntax for Charset will be something like StandartCharsets.SOME_CHARSET or Charset.forName("some_charset")

I converted BufferedImage to Base64 but How I convert it to Image again? [duplicate]

Okay, I know how to do it in C#.
It's as simple as:
Convert.ToBase64String(byte[])
and Convert.FromBase64String(string) to get byte[] back.
How can I do this in Java?
Java 8+
Encode or decode byte arrays:
byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded) // Outputs "Hello"
For more info, see Base64.
Java < 8
Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.
For direct byte arrays:
Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = codec.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(codec.decodeBase64(encoded));
println(decoded) // Outputs "Hello"
Spring
If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils class more ergonomic:
For direct byte arrays:
byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded)) // Outputs "Hello"
Android (with Java < 8)
If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64.
For direct byte arrays:
byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte [] decoded = Base64.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.decode(encoded));
println(decoded) // Outputs "Hello"
Use:
byte[] data = Base64.encode(base64str);
Encoding converts to Base64
You would need to reference commons codec from your project in order for that code to work.
For java8:
import java.util.Base64
Additionally, for our Android friends (API Level 8):
import android.util.Base64
...
Base64.encodeToString(bytes, Base64.DEFAULT);
In case you happen to be using Spring framework along with java, there is an easy way around.
Import the following.
import org.springframework.util.Base64Utils;
Convert like this.
byte[] bytearr ={0,1,2,3,4};
String encodedText = Base64Utils.encodeToString(bytearr);
To decode you can use the decodeToString method of the Base64Utils class.

Base64 string conversion to byte array not working properly

I'm trying to convert Base64 string into byte array using org.apache.commons.codec.binary.Base64
byte[] image = Base64.decodeBase64("Base64 String");
and then converting byte array to Base64 like
String Base64String = Base64.encodeBase64String(image);
but the base64String is different from the original base64 string. I dont get it where I went wrong
Use encodeBase64 not encodeBase64String.

How to decode base64 in java

I am getting a base64encoded xml data in webservice response and I want to decode it in Java .
I tried org.apache.commons.codec.binary.Base64;
byte bytesEncoded[] = base64encodedStringfromWebservice.getBytes();
// Decrypt data on other side, by processing encoded data
byte[] valueDecoded= Base64.decodeBase64(bytesEncoded );
System.out.println("Decoded value is " + new String(valueDecoded));
but still some characters like (< , />) are not getting decoded properly .
Please suggest how to decode it correctly?
The getBytes method from String is platform specific. You need to specify an encoding, and later use that same encoding to decode the string. You can just use UTF8.
You also need to do the steps in reverse order: string -> base64 -> raw utf8 bytes -> base64 -> string
// ENCODE data
byte bytesEncoded[] = base64encodedStringfromWebservice.getBytes("UTF8");
// DECODE data on other side, by processing encoded data
String base64encodedStringfromWebservice = new String(bytesEncoded, "UTF8");
byte[] valueDecoded = Base64.decodeBase64(base64encodedStringfromWebservice);
System.out.println("Decoded value is " + new String(valueDecoded));
Try specifiying the charset you are using. for example, utf-8, and as you can see here: Decoding a Base64 string in Java
byte[] valueDecoded= Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded, "UTF-8"));

How to pass byte array of an Image over a soap web-service(XML) and decode this byte array on android device to convert it back to an Image

I want to send images over a web service to an android device. This web service is written in VB.net and it is being called by android device to fetch the data. I can fetch the data normally, but the issue is with Images. I have converted image into byte array, converted it into string and passed it over web service(XML) to android device. I cannot decode this String byte array back to an image on android side. How to achieve this? Any simple solution? Am I using wrong approach?
For Converting Image To String :
String imageAsString=Base64.encodeToString(byteArray, Base64.DEFAULT);
For Converting String To Image:
byte[] imageAsBytes = Base64.decode(imageAsString.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView)findViewById(R.id.ImageView);
Bitmap imgBitmap=BitmapFactory.decodeByteArray(imageAsBytes,0,imageAsBytes.length);
image.setImageBitmap(imgBitmap);
Converting a byte array to a String is a bit tricky. Since the image data may contain null bytes, the String cannot. You probably need to encode the byte array so that the String is valid. Try to use base64-encoding.
Consider the following code example:
System.Convert.ToBase64String(byteArray)
You need to decode the base64-encoded String in android as well. Here is an example for that as well:
import org.apache.commons.codec.binary.Base64;
String base64String = "... your base64 String ...";
byte[] decodedBytes = Base64.decodeBase64(base64String.getBytes());
decodedBytes will contain your original data.
We got the solution
On webservice side we used:
System.Convert.ToBase64String(byte_arr)
On Android Side we used:
byte[] decodedBytes = Base64.decode(imageByteArray[i].getBytes(),Base64.DEFAULT);
Bitmap bMap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
Thank you for help. Cheers!!!
You can use org.castor.util.Base64Encoder to encode byte array to String
byte [] doc = {37, 80, 68, 70, 45, 49, 46};
String image = new String(Base64Encoder.encode(doc));
In your web service class, use this
byte[] imageData = Base64Decoder.decode(image);

Categories