i will like to pick an images from UIImagepicker, there are PNG and JPG format in camera roll.

and i need to convert it into NSData. However i need to know if this images is UIImageJPEGRepresentation or UIImagePNGRepresentation so i could convert it.

UIImage *orginalImage = [info objectForKey:UIImagePickerControllerOriginalImage];    
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSData *orgData = UIImagePNGRepresentation(orginalImage);
有帮助吗?

解决方案

You shouldn't know or care what the internal representation of images in the camera roll is. The methods you mentioned UIImageJPEGRepresentation and UIImagePNGRepresentation return you representations of the camera roll image. It's up to you to pick which representation you want to use.

To summarize:

NSData * pngData = UIImagePNGRepresentation(originalImage);

Will return you the image representation in an NSData object, with the format PNG.

其他提示

When the delegate method imagePickerController:didFinishPickingMediaWithInfo: for UIImagePickerController is called, you get the asset URL for the particular photo picked.

[info valueForKey:UIImagePickerControllerReferenceURL]

Now this URL can be used to access the asset in the ALAssetsLibrary. Then you would need a ALAssetRepresentation of that accessed asset. From this ALAssetRepresentation we can get the UTI for that image (http://developer.apple.com/library/ios/#DOCUMENTATION/FileManagement/Conceptual/understanding_utis/understand_utis_conc/understand_utis_conc.html)

Maybe the code would make it a bit clearer :

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  if (!(picker.sourceType == UIImagePickerControllerSourceTypeCamera)) {
    NSLog(@"User picked image from photo library");
    ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
    [library assetForURL:[info valueForKey:UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset) {
      ALAssetRepresentation *repr = [asset defaultRepresentation];
      if ([[repr UTI] isEqualToString:@"public.png"]) {
        NSLog(@"This image is a PNG image in Photo Library");
      } else if ([[repr UTI] isEqualToString:@"public.jpeg"]) {
        NSLog(@"This image is a JPEG image in Photo Library");
      }
    } failureBlock:^(NSError *error) {
      NSLog(@"Error getting asset! %@", error);
    }];
  }
}

As the UTI explains, this should be a sure shot answer to how the image is stored in the photo library.

in Swift 2.2

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if (!(picker.sourceType == UIImagePickerControllerSourceType.Camera)) {
        let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL
        if assetPath.absoluteString.hasSuffix("JPG") {

        } else {

        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top