0

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

我从我的 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;

}

}

4

1 回答 1

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;
于 2012-09-04T12:14:08.853 回答