Below code is for convert file to bytearray.
public static byte[] convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
#SuppressWarnings("resource")
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}
But I need a code for convert file to binary format.
try this:
Get your byte array file:
File file= new File("path file");
byte[] fileByte=convertFileToByteArray(file);
Then convert to base64 in byte array:
byte[] file_in_base64 = Base64.encode(fileByte, Base64.DEFAULT);
Convert byte array to binary:
String toBinary( byte[] bytes )
{
StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
for( int i = 0; i < Byte.SIZE * bytes.length; i++ )
sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
return sb.toString();
}
Here the report contain the path(pathname in sdcard in string format)
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, report);
String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile);
private static String encodeFileToBase64Binary(File fileName) throws IOException {
byte[] bytes = loadFile(fileName);
byte[] encoded = Base64.encodeBase64(bytes);
String encodedString = new String(encoded);
return encodedString;
}
in the byte[] encoded line getting this error.
The method encodeBase64(byte[]) is undefined for the type Base64
String value = Base64.encodeToString(bytes, Base64.DEFAULT);
But you can directly convert it in to String .Hope this will work for you.
An updated, more efficient, Kotlin version, that bypasses Bitmaps and doesn't store entire ByteArray's in memory (risking OOM errors).
fun convertImageFileToBase64(imageFile: File): String {
return ByteArrayOutputStream().use { outputStream ->
Base64OutputStream(outputStream, Base64.DEFAULT).use { base64FilterStream ->
imageFile.inputStream().use { inputStream ->
inputStream.copyTo(base64FilterStream)
}
}
return#use outputStream.toString()
}
}
I believe these 2 sample codes will help at least someone the same way many have helped me through this platform. Thanks to StackOverflow.
// Converting Bitmap image to Base64.encode String type
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
// Converting File to Base64.encode String type using Method
public String getStringFile(File f) {
InputStream inputStream = null;
String encodedFile= "", lastVal;
try {
inputStream = new FileInputStream(f.getAbsolutePath());
byte[] buffer = new byte[10240];//specify the size to allow
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
encodedFile = output.toString();
}
catch (FileNotFoundException e1 ) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
lastVal = encodedFile;
return lastVal;
}
I will be glad to answer any question regarding to these codes.
To convert a file to Base64:
File imgFile = new File(filePath);
if (imgFile.exists() && imgFile.length() > 0) {
Bitmap bm = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
String base64Image = Base64.encodeToString(bOut.toByteArray(), Base64.DEFAULT);
}
Convert Any file, image or video or text into base64
1.Import the below Dependancy
compile 'commons-io:commons-io:2.4'
2.Use below Code to convert file to base64
File file = new File(filePath); //file Path
byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
for (int j = 0; j < b.length; j++) {
System.out.print((char) b[j]);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
} catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
byte[] byteFileArray = new byte[0];
try {
byteFileArray = FileUtils.readFileToByteArray(file);
} catch (IOException e) {
e.printStackTrace();
}
String base64String = "";
if (byteFileArray.length > 0) {
base64String = android.util.Base64.encodeToString(byteFileArray, android.util.Base64.NO_WRAP);
Log.i("File Base64 string", "IMAGE PARSE ==>" + base64String);
}
You can try this.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
...
byte[] byteArray = byteArrayOutputStream.toByteArray();
base64Value = Base64.encodeToString(byteArray, Base64.DEFAULT);
public static String uriToBase64(Uri uri, ContentResolver resolver, boolean thumbnail) {
String encodedBase64 = "";
try {
byte[] bytes = readBytes(uri, resolver, thumbnail);
encodedBase64 = Base64.encodeToString(bytes, 0);
} catch (IOException e1) {
e1.printStackTrace();
}
return encodedBase64;
}
private static byte[] readBytes(Uri uri, ContentResolver resolver, boolean thumbnail)
throws IOException {
// this dynamically extends to take the bytes you read
InputStream inputStream = resolver.openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
if (!thumbnail) {
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the
// byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
} else {
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
int thumb_width = imageBitmap.getWidth() / 2;
int thumb_height = imageBitmap.getHeight() / 2;
if (thumb_width > THUMBNAIL_SIZE) {
thumb_width = THUMBNAIL_SIZE;
}
if (thumb_width == THUMBNAIL_SIZE) {
thumb_height = ((imageBitmap.getHeight() / 2) * THUMBNAIL_SIZE)
/ (imageBitmap.getWidth() / 2);
}
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, thumb_width, thumb_height, false);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteBuffer);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
and call it in this way
String image = BitmapUtils.uriToBase64(Uri.fromFile(file), context.getContentResolver());
I want download data in a byte[] and when save it in a jpg file it's show image.
I can do it but I have problem.
if I use this code to download data it doesn't have any problem but in this case the download speed is low :
String urlAddress = urlAddresses[0];
try {
URL url = new URL(urlAddress);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
int fileLength = httpURLConnection.getContentLength();
InputStream inputStream = httpURLConnection.getInputStream();
byte[] buffer = new byte[1];
int curLength = 0;
int newLength = 0;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while((newLength = inputStream.read(buffer))>0)
{
curLength += newLength;
publishProgress(fileLength != 0 ? (curLength*100)/fileLength : -1);
byteArrayOutputStream.write(buffer);
}
if(fileLength > 0 && curLength != fileLength)
{
Byte[] result = new Byte[1];
result[0] = ERROR_FILE_LENGTH;
return result;
}
complate = true;
byte[] resultByteArray = byteArrayOutputStream.toByteArray();
Byte[] result = new Byte[resultByteArray.length];
for(int i=0; i<result.length; i++)
result[i] = resultByteArray[i];
return result;
}
catch (IOException e)
{
e.printStackTrace();
Byte[] result = new Byte[1];
result[0] = ERROR_DOWNLOAD_FAILED;
return result;
}
but if i change this line : byte[] buffer = new byte[1] to byte[] buffer = new byte[1024] download speed go up but when I save it in a somename.jpg file it doesn't show image
String urlAddress = urlAddresses[0];
try {
URL url = new URL(urlAddress);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
int fileLength = httpURLConnection.getContentLength();
InputStream inputStream = httpURLConnection.getInputStream();
byte[] buffer = new byte[1024];
int curLength = 0;
int newLength = 0;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while((newLength = inputStream.read(buffer))>0)
{
curLength += newLength;
publishProgress(fileLength != 0 ? (curLength*100)/fileLength : -1);
byteArrayOutputStream.write(buffer);
}
if(fileLength > 0 && curLength != fileLength)
{
Byte[] result = new Byte[1];
result[0] = ERROR_FILE_LENGTH;
return result;
}
complate = true;
byte[] resultByteArray = byteArrayOutputStream.toByteArray();
Byte[] result = new Byte[resultByteArray.length];
for(int i=0; i<result.length; i++)
result[i] = resultByteArray[i];
return result;
}
catch (IOException e)
{
e.printStackTrace();
Byte[] result = new Byte[1];
result[0] = ERROR_DOWNLOAD_FAILED;
return result;
}
note : in this case I want save data to just byte[] and save file normaly wit FileOutputStream and ... after I get full byte[] and download finished;
tahnks
change:
byteArrayOutputStream.write(buffer);
to:
byteArrayOutputStream.write(buffer, 0, newLength);
I am trying to convert the captured photos (in .jpeg format ) to hexadecimal strings but when it comes to action, it tales more than 2 minutes to return the successful conversion. Would you please tell me how to enhance the performance besides increasing the buffer size? (using in Android)
The below is my code
private String changeByteToHex(byte[] a) {
StringBuilder sb = new StringBuilder();
for (byte d : a) {
sb.append(String.format("%02X", d));
}
return sb.toString();
}
public String photoEncode(File file) {
try{
ByteArrayInputStream inStream = retrieveByteArrayInputStream(file);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] temp = new byte[8192];
int read;
while((read = inStream.read(temp)) >= 0){
outStream.write(temp, 0, read);
}
byte[] data = outStream.toByteArray();
return changeByteToHex(data);
} catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
Can I convert Bitmap to String?
And then convert the String back to the Bitmap?
Thanks in advance.
This code appears to be what you want to convert to a string:
This shows how to do both:
How to convert a Base64 string into a BitMap image to show it in a ImageView?
And this one shows converting back to a .bmp:
Android code to convert base64 string to bitmap
Google is your friend... you should always ask your friends if they know the answer first :)
Steve
Any file format
public String photoEncode(File file){
try{
byte[] byteArray = null;
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024*8];
int bytesRead =0;
while ((bytesRead = bufferedInputStream.read(b)) != -1)
{
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
bos.flush();
bos.close();
bos = null;
return changeBytetoHexString(byteArray);
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
private String changeBytetoHexString(byte[] buf){
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i)
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}