从插槽接收后,Android字节数组到位图结果为空

时间:2013-09-04 12:28:56

标签: android

我创建了一个服务器,它从c ++客户端接收字节数组,客户端发送图像作为uchar数组(使用opencv),在android上我正确地接收数据。 android上的服务器将数据存储到字节数组,我需要将此字节数组转换为Bitmap。但是在使用BitmapFactory.decodeByteArray之后我得到了空位图。

这是我的服务器代码,它接收数据并存储到字节数组

class imageReciver extends Thread {
public static byte imageByte[];
private ServerSocket serverSocket;
InputStream in;
int imageSize=921600;//expected image size 640X480X3

   public imageReciver(int port) throws IOException{
      serverSocket = new ServerSocket(port);
   }

   public void run()
   {
    Socket server = null;   
    server = serverSocket.accept();

    in = server.getInputStream();       
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte buffer[] = new byte[1024];         
    int remainingBytes = imageSize; //

    while (remainingBytes > 0) {
       int bytesRead = in.read(buffer);
       if (bytesRead < 0) {
         throw new IOException("Unexpected end of data");
       }
     baos.write(buffer, 0, bytesRead);
     remainingBytes -= bytesRead;
     }
    in.close();         
    imageByte = baos.toByteArray();   
    baos.close();
    server.close();

     //Here conver byte array to bitmap
     Bitmap bmp = BitmapFactory.decodeByteArray(imageByte, 0,imageByte.length);

     return;      
     }
   }

1 个答案:

答案 0 :(得分:0)

我似乎你的代码不正确,试试这个:

try {
      URL myURL = new URL(url);
      final BufferedInputStream bis = new BufferedInputStream(myURL.openStream(), 1024);
      final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
      BufferedOutputStream out = new BufferedOutputStream(dataStream,1024);
      copy(bis, out);
      out.flush();
      final byte[] data = dataStream.toByteArray();
      BitmapFactory.Options bfo = new BitmapFactory.Options();
      bfo.inSampleSize = 2;
      Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length, bfo);
      bis.close(); 
      //use the bitmap...
}
catch (Exception e) {
      //handle ex
}