2016-08-30 86 views
0

我从图像选择器中选择了UIImage。然后,我想将所选图像作为字节数组传递给服务器。所以在这个代表中,我得到了像我这样选择的图像的路径。如何将UIImagePicker图像转换为字节数组objective-c

-(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总是得到零。这是为什么?请帮帮我。 感谢

+0

看到我更新的代码.. – vaibhav

回答

0

PLZ使用

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]); 
1

内使用方法如下代码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; 
0
- (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]; 


} 
相关问题