如何获取流字节并转换回图像 - IOS

时间:2012-09-04 07:39:23

标签: ios image stream byte nsinputstream

如何获取流字节并转换回图像,下面是我的代码。 但我得到的图像是空白的。为什么? 代码出了什么问题?

我从NSOutputStream获取字节并转换回NSData,然后将NSData转换为图像。

(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

switch (streamEvent) {

case NSStreamEventOpenCompleted:
    NSLog(@"Stream opened");
    break;
case NSStreamEventHasBytesAvailable:

    if (theStream == inputStream) {

        uint8_t buffer[5000]; 
        int len;

        while ([inputStream hasBytesAvailable]) {
            len = [inputStream read:buffer maxLength:sizeof(buffer)];
            NSLog(@"len=%d", len);
            if (len > 0) {

                NSData *pictureData = [NSData dataWithBytes:buffer length:len];

                UIImage *imagess = [[UIImage alloc]initWithData:pictureData];
                [imagesview setImage:imagess];




                                }

        }
    }
    break;

}

}

1 个答案:

答案 0 :(得分:1)

在使用NSOutPutStream时,这有点令人困惑。虽然您可能正在使用一个(远端)发送图像数据,但您必须使用NSInputStream来接收它,不是吗?

你应该做些什么?NSStreamEventHasBytesAvailable:'只是将数据附加到可变数据对象。当你最终得到NSStreamEventEndEncountered'时,就是你得到你的形象:

{
  NSMutableData *data; // ivar
}

  // init it somewhere
  data = [NSMutableData new];

case NSStreamEventHasBytesAvailable:

if (theStream == inputStream) {

    uint8_t buffer[5000]; 
    int len;

    while ([inputStream hasBytesAvailable]) {
        len = [inputStream read:buffer maxLength:sizeof(buffer)];
        NSLog(@"len=%d", len);
        if (len > 0) {
            [data appendBytes:(const void *)buffer length:len];
        }
    }
}
break;

case NSStreamEventEndEncountered:
{
    if (theStream == inputStream) {
        UIImage *imagess = [[UIImage alloc]initWithData:data];
        [imagesview setImage:imagess];
    }
}   break;