Data sharing over WiFi - android

I have establish WiFi connection between two android devices. Now I want to send Bitmap from server to client. I use the following code to send Bitmap from server to Client:
server code:
outputStream = hostThreadSocket.getOutputStream();
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 20,stream);
byte[] byteArray = stream.toByteArray();
String str =Base64.encodeToString(byteArray,0);
msgReply+=" "+str;
outputStream.write(str.getBytes());
outputStream.flush();
outputStream.close();
client code:
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString();
}
byte[] temp_arr = new byte[1024];
String[] safe = response.split("=");
try{
temp_arr=Base64.decode(safe[0], 0);
}catch (Exception e){
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeByteArray(temp_arr,0,temp_arr.length);
ImageView img=(ImageView)findViewById(R.id.imgView);
img.setImageBitmap(bmp);

Related

Why I am getting FileNotFoundException while converting Video Uri to Bytearray?

I am converting Video Uri to bytearray but I am getting FileNotFoundException
I have written this code for converting Video Uri to bytearray
video = data.getData();
byte[] buf = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis;
try {
fis = new FileInputStream(new File(video.getPath()));
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
fis.close();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
bbytes= baos.toByteArray();
Try open stream with ContentResolver:
fis = context.getContentResolver().openInputStream(video);

Not able to convert image from url into byte array

I am new to android and I need to save image from url into db and fetch it from db. I an converting image from link into byte array but getting the following error:
Cannot Resolve ByteArrayBuffer
This is the code:
private byte[] getLogoImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Update your method getLogoImage() as below.
Use AsyncTask and call this method from doInBackground().
Here is the working code. Try this:
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
while ((read = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, read);
}
baos.flush();
return baos.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Try like this
Bitmap bm = null;
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
byte[] imageArray = getBytes(bm);
and after this use below method
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
return stream.toByteArray();
}
Use This
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
Bitmap bitmap = BitmapFactory.decodeFile(url,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();

Convert a file (<100Mo) in Base64 on Android

I am trying to convert a file from the sdcard to Base64 but it seems the file is too big and i get an OutOfMemoryError.
Here is my code :
InputStream inputStream = null;//You can get an inputStream using any IO API
inputStream = new FileInputStream(file.getAbsolutePath());
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();
attachedFile = Base64.encodeToString(bytes, Base64.DEFAULT);
Is there a way to go around the OutOfMemoryError while filing the String attachedFile ?
Base64 encoding takes 3 input bytes and converts them to 4 bytes. So if you have 100 Mb file that will end up to be 133 Mb in Base64. When you convert it to Java string (UTF-16) it size will be doubled. Not to mention that during conversion process at some point you will hold multiple copies in memory. No matter how you turn this it is hardly going to work.
This is slightly more optimized code that uses Base64OutputStream and will need less memory than your code, but I would not hold my breath. My advice would be to improve that code further by skipping conversion to string, and using temporary file stream as output instead of ByteArrayOutputStream.
InputStream inputStream = null;//You can get an inputStream using any IO API
inputStream = new FileInputStream(file.getAbsolutePath());
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
output64.close();
attachedFile = output.toString();
// 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;
}

Android Byte Array to Bitmap Results Null After Receiving From Socket

I have created a server which receives byte array from a c++ client, the client send image as uchar array(using opencv) and on the android I am receiving the data correctly. The server on android store data to byte array and I need to convert this byte array to Bitmap. But I am getting null Bitmap after using BitmapFactory.decodeByteArray.
Here is my server code which receives data and store in to byte array
class imageReciver extends Thread {
public static byte imageByte[];
private ServerSocket serverSocket;
InputStream in;
int imageSize=921600;//expected image size 640X480X3
public imageReciver(int port) throws IOException{
serverSocket = new ServerSocket(port);
}
public void run()
{
Socket server = null;
server = serverSocket.accept();
in = server.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int remainingBytes = imageSize; //
while (remainingBytes > 0) {
int bytesRead = in.read(buffer);
if (bytesRead < 0) {
throw new IOException("Unexpected end of data");
}
baos.write(buffer, 0, bytesRead);
remainingBytes -= bytesRead;
}
in.close();
imageByte = baos.toByteArray();
baos.close();
server.close();
//Here conver byte array to bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(imageByte, 0,imageByte.length);
return;
}
}
I seems your code is not correct, try this:
try {
URL myURL = new URL(url);
final BufferedInputStream bis = new BufferedInputStream(myURL.openStream(), 1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
BufferedOutputStream out = new BufferedOutputStream(dataStream,1024);
copy(bis, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length, bfo);
bis.close();
//use the bitmap...
}
catch (Exception e) {
//handle ex
}

Android : How to determine the file extension of a file

I am trying to share files between two Android phones using Socket programming. The problem is right now I have to hard code the file extension on the receiving end. Is there a way that I can automatically determine the extension of the file being received?
Here's my code.
Client Side
socket = new Socket(IP,4445);
File myFile = new File ("/mnt/sdcard/Pictures/A.jpg");
FileInputStream fis = null;
fis = new FileInputStream(myFile);
OutputStream os = null;
os = socket.getOutputStream();
int filesize = (int) myFile.length();
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fis.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
System.out.println("SO sendFile" + bytesRead);
}
os.flush();
os.close();
fis.close();
socket.close();
}
And the Server side
FileOutputStream fos = null;
File root = Environment.getExternalStorageDirectory();
fos = new FileOutputStream(new File(root,"B.jpg")); //Here I have to hardcode B.jpg with jpg extension.
BufferedOutputStream bos = new BufferedOutputStream(fos);
ServerS = new ServerSocket(4445);
clientSocket = ServerS.accept();
InputStream is = null;
is = clientSocket.getInputStream();
int bytesRead = 0;
int current = 0;
byte [] mybytearray = new byte [329];
do {
bos.write(mybytearray,0,bytesRead);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
} while(bytesRead > -1);
bos.flush();
bos.close();
clientSocket.close();
}
You can find the file extension pretty easily by doing this:
String extension = filename.substring(filename.lastIndexOf('.'));

Categories

Resources