【发布时间】:2014-10-17 03:16:34
【问题描述】:
我正在尝试从每 5 秒发送一次图像的远程服务器接收图像。现在,在 Android 端,我正在使用 decodeByteArray() 将其转换为位图。运行时,有时会在屏幕上显示图像,有时会显示黑屏,LogCat 显示skimagedecoder 工厂返回null。我不知道问题是什么。
这是我的代码:
public class connection extends AsyncTask {
@Override
protected Object doInBackground(Object... arg0) {
int i = 0;
try {
clientSocket = new Socket("134.129.125.126", 8080);
input = clientSocket.getInputStream();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
data = new byte[2048 * 2048];
try {
read = input.read(data, 0, data.length);
System.out.println("getInputStream()");
bitmap = BitmapFactory.decodeByteArray(data, 0, read);
System.out.println("deco");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println(e);
}
runOnUiThread(new Runnable() {
public void run() {
image.setImageBitmap(bitmap);
System.out.println("setImage at less than 500");
}
});
}
}
}
更新 现在,尝试从服务器接收图像的大小,并使其成为正确大小的字节数组。然后decodeByteArray(),又变成Factory返回Null。这是我修改后的代码:
public class connection extends AsyncTask {
@Override
protected Object doInBackground(Object... arg0) {
try {
clientSocket = new Socket("134.129.125.126", 8080);
System.out.println("client connect to server");
input = clientSocket.getInputStream();
System.out.println("getinputstream");
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// while (true) {
int totalBytesRead = 0;
int chunkSize = 0;
int tempRead = 0;
String msg = null;
// byte[] data = null;
byte[] tempByte = new byte[1024 * 1024 * 4];
try {
tempRead = input.read(tempByte);
System.out.println("read:" + tempRead);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (tempRead < 2000) {
String message = new String(tempByte, 0, tempRead);
msg = message.substring(0, 6);
System.out.println("message head:" + msg);
byteSize = Integer.parseInt(msg);
System.out.println("ByteSize:" + byteSize);
data = new byte[byteSize];
}
try {
while (chunkSize > -1) {
System.out.println("data length:" + data.length);
chunkSize = input.read(data, totalBytesRead, data.length
- totalBytesRead);
System.out.println("chunkSize is " + chunkSize);
totalBytesRead += chunkSize;
System.out.println("Total byte read " + totalBytesRead);
if (totalBytesRead == data.length) {
if (input.read() != -1) {
// error, the file is larger than our buffer
throw new RuntimeException("Buffer overflow error!");
}
}
}
} catch (Exception e) {
}
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
System.out.println("deco");
runOnUiThread(new Runnable() {
public void run() {
image.setImageBitmap(bitmap);
System.out.println("setImage at less than 500");
}
});
return null;
}
}
【问题讨论】:
标签: android image-processing bitmap