简体   繁体   中英

How to convert UIImagePicker image into a byte array objective-c

I am selecting a UIImage from image picker. Then I want to pass my selected image as a byte array to the server. so in this delegate I am getting the path of my selected image like this.

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info

filePath=info[UIImagePickerControllerReferenceURL];

Then convert into a byte array I do like this.

NSData *data = [NSData dataWithContentsOfURL:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
NSLog(@"----BITE DATA----%@",byteData);

but this data always get nil. why is that? Please help me. Thanks

inside method didFinishPickingMediaWithInfo get image using below code.

- (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"];
}

Now show it to anywhere using below code.

NSData *imageData = [[NSUserDefaults standardUserDefaults] valueForKey:@"imageData"];
UIImage *image = [UIImage imageWithData:imageData];
self.imageView.image = image;

plz use this

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


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM