如何编写UIImage并将数据发送到接收服务器。我试过但是NSOutputStream只能在流中写入最大136768个字节而且我只保存了一小部分图像。非常感谢您的帮助。这是我的代码:
来自UIImage选择器
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = info[UIImagePickerControllerOriginalImage];
NSData *imgData = UIImageJPEGRepresentation(image,1.0f);
NSLog(@"%d",imgData.length);
NSMutableData *completeData = [[NSMutableData alloc]init];
[completeData appendData:imgData];
NSInteger bytesWritten = 0;
while ( completeData.length > bytesWritten )
{
//sending NSData over to server
NSInteger writeResult = [outputStream write:[completeData bytes]+bytesWritten maxLength:[completeData length]-bytesWritten];
if ( writeResult == -1 )
NSLog(@"error code here");
else
bytesWritten += writeResult;
if (bytesWritten == writeResult) {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
}
流委托
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
#pragma unused(aStream)
assert(aStream == self.networkStream);
switch (eventCode) {
case NSStreamEventOpenCompleted: {
[self _updateStatus:@"Opened connection"];
} break;
case NSStreamEventHasBytesAvailable: {
if (aStream == self.networkStream) {
uint8_t buffer[5000];
int len;
while ([self.networkStream hasBytesAvailable]) {
len = [self.networkStream read:buffer maxLength:sizeof(buffer)];
NSLog(@"len=%d", len);
if (len > 0) {
NSData *pictureData = [NSData dataWithBytes:buffer length:len];
[sharedManager.pictureMutableData appendData:pictureData];
NSLog(@"%d",sharedManager.pictureMutableData.length);
}
}
}
case NSStreamEventHasSpaceAvailable: {
[self _didReceiveDataImage:sharedManager.pictureMutableData];
NSLog(@"%d",sharedManager.pictureMutableData.length);
} break;
case NSStreamEventErrorOccurred: {
[self _stopReceiveWithStatus:@"Stream open error"];
} break;
case NSStreamEventEndEncountered: {
// ignore
} break;
default: {
assert(NO);
} break;
}
}
答案 0 :(得分:0)
你的代码很奇怪:
您实现输入流(NSStreamEventHasBytesAvailable
)的事件。
数据不是一部分编写的,但您必须逐个发送。部件的大小由OS决定。如果数据较大,则必须在事件NSStreamEventHasSpaceAvailable
的委托方法中编写下一部分。但你不写那里。而是设置 收到的数据!
看看这里: