I am using the Android javax API to encrypt a string which returns a byte array which I again convert into String (purpose is to write to textfile later).
Now using this String, I convert to byte array to decrypt which returns another byte array which I convert again to String.
I could not get this to work. I narrowed down the issue to the string conversion to byte array portion. Because if i use the encrpted byte array to decrypt and then get the String it works.
Not sure what's the issue. I have used the following for the conversion:
String str;
Byte [] theByteArray = str.getBytes("UTF-8");
String val = new String (theByteArray , "UTF-8");
and
Byte [] theByteArray = str.getBytes();
String val = new String (theByteArray);
What is the best way to convert from byte array to string and vice versa without losing anything?
You can use apache library's Hex class. It provides decode and encode functions.
String s = "42Gears Mobility Systems";
byte[] bytes = Hex.decodeHex(s.toCharArray());
String s2 = new String(Hex.encodeHex(bytes));
If you really need another way to store the byte array to string and vice versa, the best way is to use Base64 encoding so that you don't lose any data. Here is the link where you can download the zip. Extract the zip and include the class file in your project. Then use the following code snippets wherever you need to encode and decode.
//To encode the data and convert into a string
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitMap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
//To decode the data into byte array again
try{
byte[] ba3 = Base64.decode(ba1);
}catch(Exception e)
{
}
Related
I am trying to convert audio file to the byte array, but it seems it is not getting converted correctly. I am recording sound using mic, then converting that file to byte array using file's path on the device.
The desired byte array should be like 0x12323
But it is coming like this string [B#14746f6
Below is the code to convert audio to byte array
file is the path of the file on the device. File type is amr
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while (read != -1) {
read = fis.read(buffer);
if (read != -1)
out.write(buffer,0,read);
}
out.close();
byte[] bytes = out.toByteArray();
Log.e("byte array" ,bytes.toString());
String path= ""; // Audio File path
InputStream is= new FileInputStream(path);
byte[] arr= readByte(is);
Log.e("byte: ",""+ Arrays.toString(arr));
I solved this issue after talking to api guy. I converted byte array to base64 string and passed it. Which resolved the issue.
I need to make API in Json to send the video. I don't want to send the path of video. What is the best way to send the video in JSON which will be used by android and iPhone guys. If I use the base64 or byte[] then I am getting the memory exception error.
File file = new File("video.mp4");
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
This is how you add a video byte by byte inside an byte array. You just then send the byte array as JSONOBject by following...
byte[] data; //array holding the video
String base64Encoded = DatatypeConverter.printBase64Binary(data); //You have encoded the array into String
now send that to server. (I am guessing you know how to)..
This is how you will decode your JSON to byteArray again.
byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded);
The typical way to send binary in json is to base64 encode it. Java provides different ways to Base64 encode and decode a byte[]. One of these is DatatypeConverter.
I hope it helps.
Cheers!
Edited:
You are getting OutOfMemoryException, because HeapMemory is 2Mb in size and your video is 2Mb, so when inserting into String, it's going out of memory. Even if you put it into an Object instances, you will EITHER have to re-initialize the heap or some way else. I will try to write an answer tomorrow. (Writing this half asleep, might be other way around_
I was using the following function to convert a pdf to string:
private String GetString(String filepath) throws IOException {
InputStream inputStream = new FileInputStream(filepath);
String inputStreamToString = inputStream.toString();
byte[] byteArray = inputStreamToString.getBytes();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
I got the output as:
amF2YS5pby5GaWxlSW5wdXRTdHJlYW1ANTM1MDhmNTg=
I have found that this output is wrong. Because certainly when I encode a 2MB pdf file, it can't be so short. Actually I base64 decoded in php server and the output was an invalid pdf. So my question is what is missing in the function?
Ok. Problem solved. The following is the correct code to do this:
private String GetString(String filepath) throws IOException {
InputStream inputStream = new FileInputStream(filepath);
byte[] byteArray = IOUtils.toByteArray(inputStream);
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
Wrong part is: String inputStreamToString = inputStream.toString();. You'll not get the content of input stream as result, you'll get only something like "FileInputStream#021849".
You should read from stream in another way, e.g.: Android FileInputStream read() txt file to String
BTW, instead of reading file to String and converting it to byte array, you can read file straight to byte array.
You can solve it with the second code.
But "IOUtils" where the function code .
Was sending the collection of String Params in the Hashmap in the Api. Now it is required to add a parameter File that has to be an Image.
The body of the POST api looks as below:
Key1, Value1, Text
Key2, Value2, Text
Key3, Value3, File
I have seen many examples of Multipart requests but none solved the issue.
Looking for an approach/example.
NOTE: It's alternative way to sending Image as a File.
You can try converting Image to BASE64 String, and send it as a string.
First, convert your bitmap to byte array:
//can use lower value than 100 for more compression or change compression format as JPEG
ByteArrayOutputStream bAOS = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bAOS);
byte[] byteArray = bAOS.toByteArray();
Then, encode it to BASE64 String:
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
Finally put it to your hashmap as a String.
I have the code below to decode a bitmap to a base64 string.
for(String e:paths)
{
String usepath=e.replace("%", "//");
Bitmap m=BitmapFactory.decodeFile(usepath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
m.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String bb= Base64.encodeToString(b, Base64.NO_WRAP);
Log.e("Photo", bb);
String usepath prints like
/mnt/sdcard/DCIM/Camera/IMG_20140424_132023.jpg
I have saved the image on my pc and used an online tool to decode it to base64 and i got a long string of around 650kb(after uploading to google app engine) yet the string i get using the above code is like 10% of that and does not display the image .
But i can use the same image path to set an image view and it works like below
Bitmap bm= BitmapFactory.decodeFile(usepath);
holder.imageItem.setImageBitmap(bm);
Any reasons why the base64 encoding failing?
Ronald
Try adding the flag Base64.URL_SAFE to the encoding method.
Consider also that if the image is too large you may not get all the bytes you need in the String (you may try writing to a temp file previous to send the content).