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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With