我正在为Android开发一个多人绘图应用程序,我需要将每个用户制作的绘图发送给一个玩家。我为此使用服务器套接字。
我要做的第一件事是将位图转换为字节数组,因此可以使用host.write(byteArray);将其发送到主机。
Bitmap bitmapImage = drawView.getBitmap();
byte[] byteArray = getByteArray(bitmapImage);
byteArrayLength = byteArray.length;
MainWifiActivity.SendReceive host = MainWifiActivity.sendReceiveHost;
if (host != null) {
host.write(byteArray);
}
以下代码是我的SendReceive类,该类侦听inputStream然后启动一个Handler,该Handler应该将位图保存到内部存储中
public class SendReceive extends Thread {
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket s) {
socket = s;
try {
inputStream = s.getInputStream();
outputStream = s.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
int filesize;
while (socket != null) {
try {
filesize = DrawingActivity.byteArrayLength;
if(buffer.length != filesize && filesize > 0){
buffer = new byte[filesize];
}
bytes = inputStream.read(buffer,0 ,buffer.length);
if (bytes > 0) {
Message mesg = handler.obtainMessage(IMAGE_MSG, bytes, -1, buffer);
mesg.sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
处理程序:
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case IMAGE_MSG:
byte[] byteArray = (byte[]) msg.obj;
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
saveBitmapToInternalStorage(bitmap);
}
return false;
}
});
在saveBitmapToInternalStorage方法中,我得到一个java.lang.NullPointerException:尝试在一个虚拟方法上调用虚拟方法'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap $ CompressFormat,int,java.io.OutputStream)'空对象引用
private void saveBitmapToInternalStorage(Bitmap bmp) {
File directory = getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory, UUID.randomUUID().toString() + ".png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
Log.d("HELLO", "MY ERROR: " + e);
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我知道BitmapFactory.decodeByteArray返回已解码的位图,如果图像无法解码,则返回null。
但是为什么不能解码呢?
答案 0 :(得分:0)
我认为这是错误的
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
应该是
FileOutputStream fos = new FileOutputStream(myPath);
try {
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {