Image Uri to bytesarray - android

I currently have two activities. One for pulling the image from the SD card and one for Bluetooth connection.
I have utilized a Bundle to transfer the Uri of the image from activity 1.
Now what i wish to do is get that Uri in the Bluetooth activity to and convert it into a transmittable state via Byte Arrays i have seen some examples but i can't seem to get them to work for my code!!
Bundle goTobluetooth = getIntent().getExtras();
test = goTobluetooth.getString("ImageUri");
is what i have to pull it across. What would be the next step?

From Uri to get byte[] I do the following things,
InputStream iStream = getContentResolver().openInputStream(uri);
byte[] inputData = getBytes(iStream);
and the getBytes(InputStream) method is:
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}

Kotlin is very concise here:
#Throws(IOException::class)
private fun readBytes(context: Context, uri: Uri): ByteArray? =
context.contentResolver.openInputStream(uri)?.buffered()?.use { it.readBytes() }
Kotlin has convenient extension functions for InputStream like buffered,use , and readBytes.
buffered decorates the input stream as BufferedInputStream
use handles closing the stream
readBytes does the main job of reading the stream and writing into a byte array
Error cases:
IOException can occur during the process (like in Java)
openInputStream can return null. If you call the method in Java you can easily oversee this. Think about how you want to handle this case.

Syntax in kotlin
val inputData = contentResolver.openInputStream(uri)?.readBytes()

Java best practice: never forget to close every stream you open!
This is my implementation:
/**
* get bytes array from Uri.
*
* #param context current context.
* #param uri uri fo the file to read.
* #return a bytes array.
* #throws IOException
*/
public static byte[] getBytes(Context context, Uri uri) throws IOException {
InputStream iStream = context.getContentResolver().openInputStream(uri);
try {
return getBytes(iStream);
} finally {
// close the stream
try {
iStream.close();
} catch (IOException ignored) { /* do nothing */ }
}
}
/**
* get bytes from input stream.
*
* #param inputStream inputStream.
* #return byte array read from the inputStream.
* #throws IOException
*/
public static byte[] getBytes(InputStream inputStream) throws IOException {
byte[] bytesResult = null;
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
bytesResult = byteBuffer.toByteArray();
} finally {
// close the stream
try{ byteBuffer.close(); } catch (IOException ignored){ /* do nothing */ }
}
return bytesResult;
}

use getContentResolver().openInputStream(uri) to get an InputStream from a URI. and then read the data from inputstream convert the data into byte[] from that inputstream
Try with following code
public byte[] readBytes(Uri uri) throws IOException {
// this dynamically extends to take the bytes you read
InputStream inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// 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);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
Refer this LINKs

This code works for me
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
finish();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}

public void uriToByteArray(String uri)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buf = new byte[1024];
int n;
try {
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = baos.toByteArray();
}

Use the following method to create a bytesArray from a URI in Android studio.
public byte[] getBytesArrayFromURI(Uri uri) {
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}catch(Exception e) {
Log.d("exception", "Oops! Something went wrong.");
}
return null;
}

Related

How to Convert byte[] to Uri Image

I save the image uri by using below code
public void insert (Uri image) throws SQLiteException {
SQLiteDatabase database = mdb.getWritableDatabase();
ContentValues cv = new ContentValues();
try {
InputStream iStream = getContentResolver().openInputStream(image);
byte[] inputData = com.example.tony.monthlyexpenses.Utils.getBytes(iStream);
cv.put(MyDatabaseHelper.KEY_IMAGE,inputData);
}catch(IOException ioe)
{
Log.e("A", "<saveImageInDB> Error : " + ioe.getLocalizedMessage());
}
database.insert(MyDatabaseHelper.TABLE_EXPENSES, null, cv);
database.close();
}
Utils
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
public static byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Now I want to retrieve the image and display as setImage Uri instead of setImage 'Bitmap'.
byte[] bb = cursor.getBlob(cursor.getColumnIndex("ImageReceipt"));
imageView.setImageBitmap(Utils.getImage(bb));
It depends on the contents of the array of bytes.
Let assume that your array of bytes are URI characters, you can use the following code:
byte [] buf = <your byte array>;
String s = new String(buf, "UTF-8");
Uri uri = Uri.parse(s);
But In your case it's not possible to convert image byte array to image Uri, U can save your image Uri instead of storing bitmap. so that u can read it as an image Uri and reduce memory space too.

Android bluetooth client receive xml

I'm new at android development and I'm creating simple bluetooth app that can receive xml file and save xml file values to database. But how can I receive xml file from bytes array? Is it possible? After searchinf I found this question and based ont that question I try to save byte array to file. But how I need to test it? I can't find my file in my phone.
case Constants.MESSAGE_READ:
byte[] readBuffer = (byte[]) msg.obj;
try {
String path = activity.getFilesDir() + "/myFile.xml";
Log.d("MuTestClass", path);
FileOutputStream stream = new FileOutputStream(path);
stream.write(readBuffer);
stream.close();
} catch (Exception e1) {
e1.printStackTrace();
}
break;
You can use:
class Utils{
public static InputStream openFile(String filename) throws IOException{
AssetManager assManager = getApplicationContext().getAssets();
InputStream is = null;
is = assManager.open(filename);
return new BufferedInputStream(is);
}
public static byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
}
like this:
try {
Utils.readBytes(Utils.openFile("something.xml"));
} catch (IOException e) {
e.printStackTrace();
}

How to convert a file to Base64?

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

Reading a resource sound file into a Byte array

I have cheerapp.wav or cheerapp.mp3 or some other format.
InputStream in = context.getResources().openRawResource(R.raw.cheerapp);
BufferedInputStream bis = new BufferedInputStream(in, 8000);
// Create a DataInputStream to read the audio data from the saved file
DataInputStream dis = new DataInputStream(bis);
byte[] music = null;
music = new byte[??];
int i = 0; // Read the file into the "music" array
while (dis.available() > 0) {
// dis.read(music[i]); // This assignment does not reverse the order
music[i]=dis.readByte();
i++;
}
dis.close();
For the music byte array which takes the data from the DataInputStream. I don't know what the length of that to allocate.
This is raw file from resource not a file therefore I wouldn't know the size of that thing.
You do have byte array length as you can see:
InputStream inStream = context.getResources().openRawResource(R.raw.cheerapp);
byte[] music = new byte[inStream.available()];
And then you can read whole Stream into byte array easily.
Of course I would recommend that you do check when it comes to the size and use ByteArrayOutputStream with smaller byte[] buffer if needed:
public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[10240];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, 0, buff.length)) > 0) {
baos.write(buff, 0, i);
}
return baos.toByteArray(); // be sure to close InputStream in calling function
}
If you'll be doing lots of IO operations I recommend that you make use of org.apache.commons.io.IOUtils. That way you won't need to worry too much about quality of your IO implementation and once you import JAR into your project you would just do:
byte[] payload = IOUtils.toByteArray(context.getResources().openRawResource(R.raw.cheerapp));
Hope it will help.
Create an sdcard path:
String outputFile =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
Convert as a file and have to call the byte array method:
byte[] soundBytes;
try {
InputStream inputStream =
getContentResolver().openInputStream(Uri.fromFile(new File(outputFile)));
soundBytes = new byte[inputStream.available()];
soundBytes = toByteArray(inputStream);
Toast.makeText(this, "Recordin Finished"+ " " + soundBytes, Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
}
method:
public byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while (read != -1) {
read = in.read(buffer);
if (read != -1)
out.write(buffer,0,read);
}
out.close();
return out.toByteArray();
}
In Kotlin use
InputStream.readBytes()

Download image(SSL) and store it on SDcard in Android?

I need to download a single image at time from the Internet and then save it on the SD card. How do I do it? I have made an attempt, but when I try to view that downloaded image, it shows the message, "No Preview Available". Please see my code below:
public class ImgDownloader {
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static final byte[] downloadImage(String imgURL) {
byte[] data = null;
try {
Log.v("Down", "1");
InputStream in = null;
BufferedOutputStream out = null;
in = new BufferedInputStream(new URL(imgURL).openStream(), 8 * 1024);
Log.v("Down", "2");
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
Log.v("Down", "3");
data = dataStream.toByteArray();
// bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.v("Down", "4");
} catch (Exception ex) {
ex.printStackTrace();
// System.out.println("Exception in Image Downloader .."
// +ex.getMessage());
}
return data;
}
private static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
Note:
i have download the image from the SSL connection.
Any ideas? Thanks in advance.
You can try something like
try{
URL url = new URL(downloadUrl); //you can write here any link
File file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
//Create parent directory if it doesn't exists
if(!new File(file.getParent()).exists())
{
System.out.println("Path is created " + new File(file.getParent()).mkdirs());
}
file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
file.createNewFile();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
FileOutputStream fos = new FileOutputStream(file);
int size = 1024*1024;
byte[] buf = new byte[size];
int byteRead;
while (((byteRead = is.read(buf)) != -1)) {
fos.write(buf, 0, byteRead);
bytesDownloaded += byteRead;
}
/* Convert the Bytes read to a String. */
fos.close();
}catch(IOException io)
{
networkException = true;
continueRestore = false;
}
catch(Exception e)
{
continueRestore = false;
e.printStackTrace();
}
Make the appropriate changes according to your requirement. I use the same code for downloading files from internet and saving it to SDCard.
Hope it helps !!

Categories

Resources