2016-08-30 87 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]; 


} 
相關問題