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 .
Related
I have a question, how can I send my audio file to my server, I had tried to convert to base64 but nothing is working. This is my code
declaration of variables:
private MediaRecorder grabacion;
private String archivoSalida = null;
audio obtained with media record:
archivoSalida = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Myrecord.mp3";
grabacion = new MediaRecorder();
grabacion.setAudioSource(MediaRecorder.AudioSource.MIC);
grabacion.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
grabacion.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
grabacion.setOutputFile(archivoSalida);
Convert to base64,the error comes out here:
private String convertirAudString(MediaRecorder audio){
ByteArrayOutputStream array=new ByteArrayOutputStream();
byte[] audioByte = new byte[(int)audio.length()];//error in this line
String audioString = Base64.encodeToString(audioByte,Base64.DEFAULT);
return audioString;
}
Thanks for your all suggestion.
I solve this, with using
File file = new File(Environment.getExternalStorageDirectory() + "/Miaudio.mp3");
byte[] bytes = new byte[0];
bytes = FileUtils.readFileToByteArray(file);
Then I convert it to base64; it works for me very fast.
I am working on a android project where i am converting the image into BASE 64 format and i am able to get the string, but i am unable to store this huge String what i am getting in a string.
I need to pass the resulting string as a parameter to API. but i am getting only half image like below
Because i am getting half image the data is not getting stored properly in the database
If you copied the string from the Logcat then you got only the first part of the string as logging to logcat logs only the first part of long strings.
Better save the base64 string to file. Open in a text editor and then copy and paste.
It might help you -
public void onImageCompress(Bitmap image) {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
String ba1= Base64.encodeToString(ba, Base64.DEFAULT);
generateNoteOnSD("imagebytes.txt", ba1 + "");
}
public void generateNoteOnSD(String sFileName, String sBody) {
try {
File root = new File(getExternalFilesDir(sFileName), "image");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
System.out.println("Saved");
} catch (IOException e) {
e.printStackTrace();
}
}
Call onImageCompress method and pass your bitmap. This will generate a file with a string. Now use this link (as you used in your question) convert base64 to image to see the image.
First of all try to test with small sized images then go for big one.
in my android application i encode a video as base 64 like this.
File file=new File(path);
InputStream is = new FileInputStream(file);
int length = (int)file.length();
byte[] bytes = new byte[length];
int a=is.read(bytes,0,length);
String str = Base64.encodeToString(bytes, 0);
is.close();
//send the string to my server....
PHP
$str=$_POST['str'];
$var=base64_decode($str);
$fp = fopen('2013-02-21_14-52-35_968.mp4', 'w');
fwrite($fp,$var);
fclose($fp);
So when the video file is Written, i cant open it. How i can correctly encode a video and decode it from PHP? or what im missing thanks in advanced.
I solve my problem, the issue was I only encode one part of the file. Here my solution:
$fp=fopen("/address".$filename,'w')
while($row=mysql_fetch_array($getChunks)){
$chuncks=$row['chunkpart'];
$var=base64_decode($chunks);
fwrite($fp,$var)
}
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)
{
}
I am uploading my image on server using Base64 as-
private String convertBitmapToString(ImageView imgview) {
imgview.buildDrawingCache();
Bitmap objbmap = imgview.getDrawingCache();
ByteArrayOutputStream objbitmapArrayStream = new ByteArrayOutputStream();
objbmap.compress(Bitmap.CompressFormat.JPEG, 90, objbitmapArrayStream);
byte[] objbitmaparray = objbitmapArrayStream.toByteArray();
String img_string = Base64.encodeBytes(objbitmaparray);
return img_string;
}
And When I want to Show That Image Hit Again Php Server Which give me response as-
"picture":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT\/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT\/wAARCABGAEcDASIAAhEBAxEB\/8QAHwAAAQUBAQEBAQE"
I am unable to decode it please suggest .
Well server gives you base64 encoded picture obviously, because online base64 decoder showed this when i decoded your string:
�JFIF�������C�
which is a sign of a correct image content, so just decode it.
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);