如何将UIImagePicker图像转换为字节数组objective-c
Posted
技术标签:
【中文标题】如何将UIImagePicker图像转换为字节数组objective-c【英文标题】:How to convert UIImagePicker image into a byte array objective-c 【发布时间】:2016-08-30 07:10:20 【问题描述】:我正在从图像选择器中选择UIImage
。然后我想将我选择的图像作为字节数组传递给服务器。所以在这个委托中,我得到了我选择的图像的路径。
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
filePath=info[UIImagePickerControllerReferenceURL];
然后转换成我喜欢这样的字节数组。
NSData *data = [NSData dataWithContentsOfURL:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
NSLog(@"----BITE DATA----%@",byteData);
但是这个data
总是为零。这是为什么?请帮我。
谢谢
【问题讨论】:
查看我更新的代码.. 【参考方案1】:请使用这个
UIImage *Image = (UIImage*)[info valueForKey:UIImagePickerControllerOriginalImage];
NSData *imgData = UIImageJPEGRepresentation(Image, 1); //1 it represents the quality of the image.
NSLog(@"Size of Image(bytes):%d",[imgData length]);
【讨论】:
【参考方案2】:内部方法didFinishPickingMediaWithInfo
使用以下代码获取图像。
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(chosenImage)];
NSLog(@"image string : %@",info[UIImagePickerControllerEditedImage]);
// save using nsuserdefaults or any other your local database
[[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"imageData"];
现在使用下面的代码将其显示到任何地方。
NSData *imageData = [[NSUserDefaults standardUserDefaults] valueForKey:@"imageData"];
UIImage *image = [UIImage imageWithData:imageData];
self.imageView.image = image;
【讨论】:
【参考方案3】:- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSData* imageData=UIImageJPEGRepresentation(image,1.0);
// Add selected imageData in Array and pass imageData to server
[imageDataArray addObject:imageData];
【讨论】:
以上是关于如何将UIImagePicker图像转换为字节数组objective-c的主要内容,如果未能解决你的问题,请参考以下文章