接收byte []并在ImageView android上显示它

时间:2013-12-09 15:02:56

标签: java android sockets imageview

我在做服务器/客户端实现,我需要从服务器发送一个byte [](已经转换的图像)到客户端。

我有服务器发送,客户端接收字节[],但我不能在我的imageView上绘制它。

我有以下客户端代码

类ViewerThread扩展AsyncTask Void,Void,Void> ...

public void startSharing(ImageView img_viewer) {

try {
            ObjectInputStream in_client = null;
            try {

                byte[] byteArray;
                Bitmap bmp;

                while (true) {
                    in_client = new ObjectInputStream(socket.getInputStream());
                    Log.e(TAG_THREAD, "Waitting for new image...");
                    //Log.e(TAG_THREAD, "Viewer: -> trying to read.....");
                    //Read byte[] -> image to draw
                    byteArray = (byte[])in_client.readObject();
                    Log.e(TAG_THREAD, "Received! -> " + byteArray.toString() + " size: "+ byteArray.length);

                    bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                    //-> draw
                    Log.e(TAG_THREAD, "drawing... -> " + byteArray.toString() + " size: "+ byteArray.length);

                    img_viewer.setImageBitmap(bmp);
                    img_viewer.refreshDrawableState();
                }

            } catch (Exception e) {
                System.err.println("Server - Error transfering bitmaps: "
                        + e.getMessage());
            } finally {
                in_client.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
}

寻找LogCat我有:

Waitting for new image...
Received! -> [B@4052b700 size: 293438
drawing... -> [B@4052b700 size: 293438

但它并没有从这里开始......只有当我停止服务器时,图像才会出现在我的ImageView对象中。

活动:

img_viewer = (ImageView) findViewById(R.id.img_viewer);

ViewerThread vt = new ViewerThread(getString(R.string.server_address), 
            getString(R.string.port_number));

vt.execute();

Log.e("tag", "Viewer is connected to server!");

vt.startSharing(img_viewer);

这可能是什么问题?

2 个答案:

答案 0 :(得分:2)

从您的代码示例中不清楚,但我认为此代码在UI线程中运行。

只要您的代码在while循环中,用户界面就无法刷新图片。一旦停止服务器,就会遇到异常。这留下了while循环并允许UI重绘自己。因此,你可以看到图像。

答案 1 :(得分:0)

user1907954

您可以遍历接收的字节并通过Handler将其传递给接口。我用它来监听套接字连接上的接收字节。确保套接字连接已线程化且位于后台。 Android是单线程的,如果你一次要求它做得太多就会崩溃。

final Handler handler = new Handler();
final Runnable updateUI00 = new Runnable()
{
  public void run() 
  {
     textIn.append("LOAD:" + response + "\n");
  }
};

...

(在您的套接字连接中):

while (running) 
{                   
    charsRead = in.readInt();

    if (charsRead != -1) 
    {
        response += in.substring(0, charsRead);
        handler.post(updateUI00);           
    }
}