Save Image Byte Array to .net webservice and retrieve it - java

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

Related

Convert byte array to playable mp4 file

I need to do some processing on the raw file bytes and the algorithm is fine with working on .wav file but the problem is the .mp4 files it is not playable at all.
I think the problem that the file contains raw bytes only and no header
please help me
public void convert(String maskFlag, File endFile)
{
byte[] rawData = getarr(originalFile);
byte[] effectedData = rawData.clone();
effectedData = changePitch(rawData, parameters.getPitch());
effectedData = changeVolume(effectedData, parameters.getVolume());
effectedData = changeSpeed(effectedData, parameters.getSpeed());
FileOutputStream out = new FileOutputStream(endFile);
out.write(effectedData);
out.close();
}
byte[] getarr(File file) throws Exception
{
InputStream fis = new FileInputStream(file);
fis = new FileInputStream(file);
byte [] byteArr = IOUtils.toByteArray(fis);
return byteArr;
}

Xamarin android image URI to Byte array

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;
}

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

Java socket, get image file but it doesn't open

That's my first question so I hope I write it correctly.
I am trying to send an byte[] array through a Java socket, that array contains an image.
Here is the code to send the file:
public void WriteBytes(FileInputStream dis) throws IOException{
//bufferEscritura.writeInt(dis.available()); --- readInt() doesnt work correctly
Write(String.valueOf((int)dis.available()) + "\r\n");
byte[] buffer = new byte[1024];
int bytes = 0;
while((bytes = dis.read(buffer)) != -1){
Write(buffer, bytes);
}
System.out.println("Photo send!");
}
public void Write(byte[] buffer, int bytes) throws IOException {
bufferEscritura.write(buffer, 0, bytes);
}
public void Write(String contenido) throws IOException {
bufferEscritura.writeBytes(contenido);
}
My image:
URL url = this.getClass().getResource("fuegos_artificiales.png");
FileInputStream dis = new FileInputStream(url.getPath());
sockManager.WriteBytes(dis);
My code to get the image file:
public byte[] ReadBytes() throws IOException{
DataInputStream dis = new DataInputStream(mySocket.getInputStream());
int size = Integer.parseInt(Read());
System.out.println("Recived size: "+ size);
byte[] buffer = new byte[size];
System.out.println("We are going to read!");
dis.readFully(buffer);
System.out.println("Photo received!");
return buffer;
}
public String Leer() throws IOException {
return (bufferLectura.readLine());
}
And to create an image file:
byte[] array = tcpCliente.getSocket().LeerBytes();
FileOutputStream fos = new FileOutputStream("porfavor.png");
try {
fos.write(array);
}
finally {
fos.close();
}
The image file is created but when I try to open it for example with Paint it says that it can't open it because it is damaged...
I also tried to open both images (the original and the new one) with notepad and they have the same data inside!
I don't know what is happening...
I hope you help me.
Thanks!
Don't use available() as a measure of file length. It isn't. There is a specific warning in the Javadoc about that.
Use DataOutputStream.writeInt() to write the length, and DataInputStream.readInt() to read it, and use the same streams to read the image data. Don't use multiple streams on the same socket.
Also in this:
URL url = this.getClass().getResource("fuegos_artificiales.png");
FileInputStream dis = new FileInputStream(url.getPath());
the second line should be:
InputStream in = URL.openConnection.getInputStream();
A class resource is not a file.

To read an image from Android Emulator

This is my code to convert image file into byte array.
public String GetQRCode() throws FileNotFoundException, IOException {
/*
* In this function the first part shows how to convert an image file to
* byte array. The second part of the code shows how to change byte array
* back to a image.
*/
AssetManager mgr = mAppView.getContext().getAssets();
InputStream in = mgr.open("www/Siemens_QR.jpg");
InputStreamReader isr = new InputStreamReader(in);
char[] buf = new char[20];
isr.read(buf, 0, 20);
isr.close();
// byte[] bytes = bos.toByteArray();
String abc = buf.toString();
return abc;
}
Here I am converting an image file into byte array. I am able to do this. But when try to read this image file using the path ("sdcard/Download/Siemens_QR.jpg") stored in emulator then I am getting VM aborting error. Please suggest me the correct path to read the image file stored in the emulator.
if you have jpg image stored on SD card then get the file path and try to convert the image to byte using following method...
Bitmap bitmap = BitmapFactory.decodeFile(file path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] byte_img_data = baos.toByteArray();

Categories

Resources