Not able to transfer image everytime through socket Android - android

I need to develop an application to transfer image continuously from android to android which should be received as an video on the client side..and i have two applications which one (server) will send the file through socket connected by wifi and other should the client side should recive the image which is sent...currently am just saving it in one location in the client side...am able to receive the file correctly...but the problem is am not able to send all files correctly all the time...
Means some time the image file will be transfered and some time i ll not be able to receive and when i ll not be able to receive i am getting an exception as
: java.io.UTFDataFormatException: ...and the file is not written and saved on the receiving side...
If am not able to receive images continuously...i can think there is some problem in the code..but am able to transfer it some times..and some time not able to transfer...am not able to figure what the issue is...plz any guidance
the error is:
11-18 10:38:17.351: W/System.err(1001): java.io.UTFDataFormatException: bad second or third byte at 2
11-18 10:38:17.359: W/System.err(1001): at java.nio.charset.ModifiedUtf8.decode(ModifiedUtf8.java:53)
11-18 10:38:17.359: W/System.err(1001): at java.io.DataInputStream.decodeUTF(DataInputStream.java:444)
11-18 10:38:17.359: W/System.err(1001): at java.io.DataInputStream.decodeUTF(DataInputStream.java:438)
11-18 10:38:17.359: W/System.err(1001): at java.io.DataInputStream.readUTF(DataInputStream.java:433)
and the file is not saved when i get this exception..
Many scenarios i have tested by capturing image and saving and sending...and also compressing the image and sending...in these scenarios some very rarely it is going....am not able to figure out it...
Sender code:
File myFile = new File(sdCard+"/image/image.jpg");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
//bis.read(mybytearray, 0, mybytearray.length);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
tv.setText("Send file name size to server");
//Sending file name,file size and to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
socket.close();
tv.setText("Socket Close");
tv.setText("Sent");
Receiver Code:
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
String fileName = clientData.readUTF();
File file = new File(dir,fileName);
OutputStream output = new FileOutputStream(file);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
{
output.write(buffer, 0, bytesRead);
size -= bytesRead;
System.out.println("Writing");
}
// status.setText("Received");
// Closing the FileOutputStream handle
output.close();
s.close();
Thanks and Regards,
Divya.K

I was stuck on this thing i combined few days of my search and reached to this... Try it and see if works for you..
Bitmap myBitmap = null;
try {
File imgFile = new File(imgPath);
if (imgFile.exists()) {
File image = new File(imgPath, "imagename.jpg");
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
myBitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
//myBitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true); //uncomment this if you want to scale the image
//imageView.setImageBitmap(bitmap);//to set bitmap to image view
}
Socket sock = new Socket("192.168.1.1", 80);//ip adress and port number
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (myBitmap != null) {
myBitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
}
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
BufferedInputStream bis = new BufferedInputStream(bs);
bis.read(bitmapdata, 0, bitmapdata.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(bitmapdata, 0, bitmapdata.length);
os.flush();
sock.close();
} catch (Exception e) {
e.printStackTrace();
}

Related

MediaRecorder setOutputFile socket. File not Open

Device Google Glass XE19.1
I'm try write file on remote server:
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mMediaRecorder.setVideoEncodingBitRate(0x4c4b40);
mMediaRecorder.setAudioChannels(2);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mMediaRecorder.setAudioEncodingBitRate(0x17700);
mMediaRecorder.setAudioSamplingRate(44100);
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mMediaRecorder.setOutputFile(pfd.getFileDescriptor());
On remote server file writes, but when i try open this, i get next error:
ftypisom isom3gp4 free
But when i save in sd card, it's ok. What wrong?
P.S. this test code: Works very good. File open and play
socket = new Socket(host,4444);
File file = new File("C:/video.mp4");
long length = file.length();
byte[] bytes = null;
bytes = new byte[1024];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
int count;
while((count = bis.read(bytes))>0){
dos.write(bytes, 0, count);
}
System.out.println("File send");
bos.flush();
bos.close();
fis.close();
bis.close();
socket.close();

Reading InputStream after writing

I am trying to read InputStream after writing output stream to sdcard. I have downloaded file from HttpURLConnection. File is successfuly written to sdcard. But I am trying to read inputstream from same file but contents are not being read properly. On emulator some contents are shown but on actual device contents are not shown. Can you please help what can be the issue? I am posting downloading, writing and reading code.
fileUrl = new URL(filename);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
InputStream is = connection.getInputStream();
/**
* Create file with input stream
*/
File downloadFile = new File("/sdcard/", "myFile3.pdf");
downloadFile.createNewFile();
final FileOutputStream outputStream = new FileOutputStream(downloadFile);
int availbleLength = is.available();
byte[] bytes = new byte[availbleLength];
int len1 = 0;
while ((len1 = is.read(bytes)) > 0) {
outputStream.write(bytes, 0, len1);
}
outputStream.flush();
outputStream.close();
File myFile = new File("/sdcard/myFile3.pdf");
InputStream inputStream = new FileInputStream(myFile);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
System.out.println("Byte Lenght: " + buffer.length);
inputStream.available() is only an estimate not actual length of the complete input data.
FileInputStream.available()

sending bmp usng sockets

I'm trying to send bmp image using socket. I have such code on android:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
MainActivity.bmp.compress(Bitmap.CompressFormat.JPEG, 20,
stream);
byte[] byteArray = stream.toByteArray();
OutputStream os = echoSocket.getOutputStream();
os.write(byteArray,0,byteArray.length);
os.flush();
and on PC:
String q = SockIn.readLine();
File file = new File("filename.bmp");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(q);
in bmp file I only get up to 401 bytes, which of course is corrupt bmp image. what am I doing wrong?
MODIFIED
modified PC side, now the code is:
InputStream in_ = clientSocket.getInputStream();
OutputStream out_ = new FileOutputStream("filename.bmp");
final byte[] buffer = new byte[1024];
int read = -1;
int i = 0;
while ((read = in_.read(buffer)) != -1) {
out_.write(buffer, 0, read);
System.out.println(i);
i++;
}
in_.close();
out_.close();
System.out.println("Done");
It never gets to last line( println("Done") ). when I close android program, it gets to last line and bmp opens succesfully
Your reading logic is completely off. You only use a readLine() once and then write that to file. The data that was written to the socket on the device side was binary. That means that trying to read it as if it were textual (as readLine() does) will return meaningless junk. The reason it's usually 401 bytes long is that readLine() will look for the first newline character combination and return everything up to that as a String. This is not what you want.
What you need is a loop that will read from the socket and write into the file as long as there is data in the socket. A standard copy loop should suffice here.
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream(...);
final byte[] buffer = new byte[BUFFER_SIZE];
int read = -1;
while ((read = in.read(buffer)) != -1)
out.write(buffer, 0, read);
in.close();
out.close();
Note that the above code isn't tested but something to that effect should do the trick.
Why are you reading a String if you are sending a byte ?
Try those setp one by one only if the previous did not worked.
1. Read() and don't Readline() what you are writing
If you write a byte, read a byte
Byte obj = SockIn.read();
2. Encode your array before sending
Base64.encodeBase64String(byteArray);

How to display the JPEG Image directly from byte array (Before saving Image)?

I am receiving a jpeg image (Image size: 50KB) from client socket and saving in emulator SD Card. From there I am displaying the jpg image in Imageview. But I want to display the image before saving image on the SD Card because our android appli will receive the continous images from sockets, If I follow receive, save and display method then it will become very slow process, so to increase the speed I want display from ram only. For this I need to save the image array temporarily on the RAM. From there I planed to display and save by using the separate threads. So please guide me how to display the image from byte array.
Note: I am receiving JPEG image from socket, not .bmp or .gif or .png.
Below is my code for receiving the image from tcp socket. (Its working fine)
(Note: This is done in seperate thread, don't try it in UI thread.)
public byte[] mybytearray = new byte[310000];
private int bytesRead=0;
private int current = 0;
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
Socket client = serverSocket.accept();
try {
myDir=new File("/mnt/sdcard/saved_images");
if (!myDir.exists()){
myDir.mkdir();
}else{
Log.d("ServerActivity","Folder Already created" );
}
String fpath = "/image0001.jpg";
File file = new File (myDir, fpath);
if (file.exists ()) file.delete ();
InputStream is = client.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
Log.d("ServerActivity","Reconstructing Image from array");
bos.flush();
bos.close();
fos.flush();
fos.close();
is.close();
client.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
Try inserting this code snippet into your code:
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
ByteArrayInputStream inputStream = new ByteArrayInputStream(myByteArray);
bitmap = BitmapFactory.decodeStream(inputStream);
ImageView picture = new ImageView(this);
picture.setImageBitmap(bitmap);
bos.write(mybytearray, 0 , current);
Use Bitmap, create it from Byte Array,
Bitmap bitmap;
bitmap= BitmapFactory.decodeByteArray(mybytearray, 0, mybytearray.length);
Convert byte[] to bitmap.
Try the following
ByteArrayInputStream imageStream = new ByteArrayInputStream(byte[] array);
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);

the download image be corrupted at android app

simply i need to download an image but the problem is the image get corrupted !!!
i find many way to download the image but still this problem appeared .
i try do this :
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file2 = new File(path,"DemoPictureX.png");
InputStream is=(InputStream) new URL("http://androidsaveitem.appspot.com/downloadjpg").getContent();
OutputStream os = new FileOutputStream(file2);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
i think it read just read some row from the image !!!
you need a loop and read with a smaller buffer (like 1024 bytes) from the stream.
URL url = new URL("your url here");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(targetFile);
byte buffer[] = new byte[1024];
int read;
while ((read = bis.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
fos.flush();
fos.close();
bis.close();
is.close();
This should work for you

Categories

Resources