【问题标题】:Android Byte Array to Bitmap Results Null After Receiving From Socket从套接字接收后,Android字节数组到位图结果为空
【发布时间】:2013-09-07 23:04:33
【问题描述】:

我创建了一个从 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;      
     }
   }

【问题讨论】:

    标签: android


    【解决方案1】:

    我好像你的代码不正确,试试这个:

    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
    }
    

    【讨论】:

    • 在客户端,我将 uchar 直接发送到套接字。我如何在此处使用 url...并且我在服务器端以字节流的形式获取正确的数据..转换为位图时会出现问题。
    • 参考示例代码,你必须确保你从socket读取的数据放入到包中
    猜你喜欢
    • 1970-01-01
    • 2010-11-13
    • 2023-04-10
    • 2015-03-22
    • 2012-06-08
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多