如何将UIImagePicker图像转换为字节数组objective-c

时间:2016-08-30 07:10:21

标签: ios objective-c uiimage bytearray uiimagepickercontroller

我从图片选择器中选择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总是为零。这是为什么?请帮我。 感谢

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

使用此

  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 :(得分:0)

C