我从客户端套接字接收 jpeg 图像(图像大小:50KB)并保存在模拟器 SD 卡中。从那里我在 Imageview 中显示 jpg 图像。但我想在将图像保存到SD卡上之前显示图像,因为我们的android应用程序将从套接字接收连续图像,如果我遵循接收、保存和显示方法,那么它将变得非常慢的过程,所以要提高我想要的速度仅从内存显示。为此,我需要将图像数组临时保存在 RAM 上。从那里我计划使用单独的线程来显示和保存。所以请指导我如何显示字节数组中的图像。
注意:我从套接字接收 JPEG 图像,而不是 .bmp 或 .gif 或 .png。
下面是我从 tcp 套接字接收图像的代码。 (它工作正常)
(注意:这是在单独的线程中完成的,不要在 UI 线程中尝试。)
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();
}
尝试将此代码片段插入到您的代码中:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)