0

我创建了一个服务器,它从 c++ 客户端接收字节数组,客户端将图像作为 uchar 数组(使用 opencv)发送,并且在 android 上我正确接收数据。android 上的服务器将数据存储到字节数组中,我需要将此字节数组转换为位图。但是我在使用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;      
     }
   }
4

1 回答 1

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
}
于 2013-09-04T12:48:28.147 回答