Xamarin android image URI to Byte array - java

i'm simply trying to upload image to server.
when i choose image from , i get URI to that image.
the question is how can i convert this URI to byte[] byte array?
no more no less. thats my question
this is what ive been trying.
i tried to rewrite this https://colinyeoh.wordpress.com/2012/05/18/android-convert-image-uri-to-byte-array/
to C#
public byte[] convertImageToByte(Android.Net.Uri uri)
{
byte[] data = null;
try
{
ContentResolver cr = this.ContentResolver;
var inputStream = cr.OpenInputStream(uri);
Bitmap bitmap = BitmapFactory.DecodeStream(inputStream);
var baos = new ByteArrayOutputStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, baos);
data = baos.ToByteArray();
}
catch (FileNotFoundException e)
{
e.PrintStackTrace();
}
return data;
}
but the error...
Error CS1503: Argument `#3' cannot convert `Java.IO.ByteArrayOutputStream' expression to type `System.IO.Stream' (CS1503) (Foodle.Droid)
how to fix this? or new code to get image from gallery and convert that to byte array is fine.
help!

public byte[] convertImageToByte(Android.Net.Uri uri)
{
Stream stream = ContentResolver.OpenInputStream(uri);
byte[] byteArray;
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
byteArray = memoryStream.ToArray();
}
return byteArray;
}

Related

Why I'm getting 2 different base64 encoded string from the same image (Android Studio and Netbeans)?

I need to convert an image choosen from the gallery into a base64 string.
Then, I pass the baase64 string as a parameter for an API request.
There is only one problem. When I use netbeans it works, when I use Android Studio it doesn't. I found that the problem is the base64 string output. I don't know why, if I use the same exactly image, the output is different.
Maybe the problem happpens because I have to use the same exact method to read the image file...?
That's my code in Netbeans(working):
InputStream inputStream = new FileInputStream("testImage.jpg");
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedFile = Base64.getEncoder().encodeToString(bytes);
And that's the code in Android Studio:
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageData = baos.toByteArray();
InputStream inputStream = getContentResolver().openInputStream(imageUri);
byte[] buffer_new = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer_new)) != -1) {
output.write(buffer_new, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedImage = Base64.encodeToString(bytes,Base64.DEFAULT);
Log.v("encodedImage", encodedImage);
The ouput string are almost the same only at the first char..then they are different..with the android studio encoded string, I get this error when I try to use the API.
BAD_ARGUMENTS:<key>
Error while parsing some arguments. This error may be caused by illegal type or length of argument.
What should I use to get the same base64 string?
ps. in Netbeans the image is a file in the same folder of the project, in android studio the user can load a picture from gallery.

Base64.encodeToString() not working in Android

So i have a bitmap and now i want to convert it into an imageUri (or string),
i am using this code here but its just doesn't work instead of returning the imageUri its returning a long random text.
Here is my code :
ByteArrayOutputStream baos = new ByteArrayOutputStream();
saveBitmap.compress(Bitmap.CompressFormat.JPEG, 75, baos);
String path = Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT);
And this is what i am getting :
Instead of Base64.DEFAULT, use Base64.NO_WRAP
String path = Base64.encodeToString(baos.toByteArray(),Base64.NO_WRAP);
try below way, should be work
byte[] data = convert image in byte.
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
Base64.encodeToString() encodes the byte array in a string. This isn't your uri. Rather this is your image/bitmap in Base64. You can use suitable Base64.decode to get back the byte array.
To get uri, you can use some of the other options including
Uri.fromFile(new File("your_file_path));
try {
val imageStream: InputStream? = requireActivity().getContentResolver().openInputStream(mProfileUri)
val selectedImage = BitmapFactory.decodeStream(imageStream)
val baos = ByteArrayOutputStream()
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
val encodedString: String = Base64.encodeToString(b,Base64.DEFAULT)
Log.d("check string" ,encodedString.toString())
} catch (e: IOException) {
e.printStackTrace()
}
For kotlin use this code and this is running successfully image to base64 when upload image to server . just put image uri "imageStream" here thats it.
Sorry guys, i thought Base64.encodeToString() will return me the imagePath, but i was wrong. Anyways i got the solution,
Here is the code that i have used,
ByteArrayOutputStream baos = new ByteArrayOutputStream();
saveBitmap.compress(Bitmap.CompressFormat.JPEG, 75, baos);
String path = MediaStore.Images.Media.insertImage(getContentResolver(),saveBitmap,"Title",null);

Share an image using a memory stream or byte array

I have some standard code to share an image in my Android app. The image exists on the storage and I provide an URI to the image. This all works fine.
However, this requires the WRITE_EXTERNAL_STORAGE permission. Is there a way I can share an image without the need of this permission, for example, to not save the image to storage, but specifying a memory stream or byte array?
Thanks!
You can convert an image file to a byte array with the following code, which I taken from an answer to a similar question: How to convert image into byte array and byte array to base64 String in android?
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
Optional step to encode in Base64
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Take a path of a bitmap image and convert it into Base64

I'm trying to take a path of an image like:
"content://media/external/images/media/3"
and convert it into a base64 string.
Here is the code I have now:
public String ConvertandSetImagetoBase64(String imagePath) {
String base64 = null;
byte[] input = null;
try{
FileInputStream fd = new FileInputStream(imagePath);
Bitmap bmt = BitmapFactory.decodeFileDescriptor(fd.getFD());
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap tmp = ProfileActivity.scaleDownBitmap(bmt, 10, this);
tmp.compress(Bitmap.CompressFormat.JPEG, 10, stream);
input = stream.toByteArray();
base64 = Base64.encodeToString(input, Base64.DEFAULT);
//LocalProfileActivity.input = input;
}catch(Exception e){
Log.e(LOG_TAG,"[ONACTIVITYRESULT] Could not bind input to the bytearray: " + e.getMessage());
}
}
catch (Exception e){
Log.e("LocalProfile", "ConvertandSetImagetoBase64: Could not load selected profile image");
}
return base64;
}
content://media/external/images/media/3 is what I'm passing into the the method. Can anyone help me?
Since you are specifying the location as a URI, you could try something like:
URL url = new URL(imagePath);
Bitmap bmt = BitmapFactory.decodeStream(url.openStream());

Save Image Byte Array to .net webservice and retrieve it

I have a .net ASMX webservice that I'm consuming using the ksoap2 library. In the service, I first save the user image and later retrieve it. However, once I retrieve it, the byte array is intact, but the BitmapFactory is unable to decode it and returns a null.
To convert to byte array:
Bitmap viewBitmap = Bitmap.createBitmap(imageView.getWidth(),
imageView.getHeight(), Bitmap.Config.ARGB_8888);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
viewBitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
The webservice accepts the bytearray in the byte[] format.
To convert the array into bitmap:
byte[] blob= info.get(Main.KEY_THUMB_BYTES).getBytes();
Bitmap bmp=BitmapFactory.decodeByteArray(blob,0,blob.length); // Return null :(
imageView.setImageBitmap(bmp);
From partial-analysis, it appears that the byte array does not change. Then why does decoding return null? Is there a better to save an image and pass it through a webservice? I didn't analyze the whole byte array, so I'm guessing it might've changed a bit.
Any thoughts? Many thanks!
UPDATE:
I just tried converting the byte[] to string using:
Base64.encodeToString( bos.toByteArray(), Base64.DEFAULT);
And decode using:
byte[] blob= Base64.decode(info.get(Main.KEY_THUMB_BYTES));
Now all i get is a White picture. I'm not sure what's wrong here. Please help.
UPDATE:
I'm storing this image inside of a database, in a column of type varchar(max). Should I be storing this byte array string inside a different sql data type? I'm not too experienced with SQL, so I used varchar because it did not convert text to unicode, which I thought might be good for thie byte array.
Thanks!
convert your byte arrays to Base64 that is a string and easy to transfer:
public static String bitmapToBase64(Bitmap bitmap) {
byte[] bitmapdata = bitmapToByteArray(bitmap);
return Base64.encodeBytes(bitmapdata);
}
public static byte[] bitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
return bitmapdata;
}
and
public static Bitmap base64ToBitmap(String strBase64) throws IOException {
byte[] bitmapdata = Base64.decode(strBase64);
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0,
bitmapdata.length);
return bitmap;
}
also you can do it not only on image files but also on every file types:
public static String fileToBase64(String path) throws IOException {
byte[] bytes = fileToByteArray(path);
return Base64.encodeBytes(bytes);
}
public static byte[] fileToByteArray(String path) throws IOException {
File imagefile = new File(path);
byte[] data = new byte[(int) imagefile.length()];
FileInputStream fis = new FileInputStream(imagefile);
fis.read(data);
fis.close();
return data;
}
public static void base64ToFile(String path, String strBase64)
throws IOException {
byte[] bytes = Base64.decode(strBase64);
byteArrayTofile(path, bytes);
}
public static void byteArrayTofile(String path, byte[] bytes)
throws IOException {
File imagefile = new File(path);
File dir = new File(imagefile.getParent());
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(imagefile);
fos.write(bytes);
fos.close();
}

Categories

Resources