我目前正在使用远程桌面应用。服务器部分在Android设备上运行,客户端在PC / Raspberry PI上运行。我在接收位图时遇到了问题(来自Android的截图,作为字节数组发送)。 Android Server 代码如下所示:
//os = new ObjectOutputStream(s.getOutputStream());
public void run() {
while(true){
try {
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
int quality = 100;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
byte[] byteArray = stream.toByteArray();
if(byteArray.length>0) {
os.writeInt(byteArray.length);
os.write(byteArray, 0, byteArray.length);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
}}}
PC上的 Receiver App 就像这样:
//ois = new ObjectInputStream(s.getInputStream());
public void run() {
while(true){
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int size = ois.readInt();
System.out.println(size);
byte[] data = new byte[size];
int length = 0;
while ((length = ois.read(data,0,size)) != -1) {
out.write(data, 0, size);
out.flush();
}
byte[] bytePicture = out.toByteArray();
out.close();
BufferedImage buffImage = byteArrayToImage(bytePicture);
ImageIcon imgIcon = new ImageIcon(buffImage);
l.setIcon(imgIcon);
} catch (IOException e) {
}}}
byteArrayToImage
public static BufferedImage byteArrayToImage(byte[] bytes) {
BufferedImage bufferedImage = null;
try {
InputStream inputStream = new ByteArrayInputStream(bytes);
bufferedImage = ImageIO.read(inputStream);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return bufferedImage;
}
问题是在接收器应用程序中我得到Java OutOfMemoryException,因为我在传入的屏幕截图之间无法区分。我真的无法弄清楚如何准确读取位图的大小(作为字节数组)然后显示它并读取另一个和另一个。任何帮助将不胜感激。提前谢谢。