如何知道这个图像是jpg或png iphone

时间:2012-04-20 02:10:00

标签: iphone ios xcode uiimagejpegrepresentation uiimagepngrepresentation

我想从UIImagepicker中选择一张图片,在相机胶卷中有PNG和JPG格式。

我需要将其转换为NSData。但是我需要知道这些图片是UIImageJPEGRepresentation还是UIImagePNGRepresentation,所以我可以转换它。

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

3 个答案:

答案 0 :(得分:11)

您不应该知道或关心相机胶卷中图像的内部表示。您提到的方法UIImageJPEGRepresentationUIImagePNGRepresentation会返回相机胶卷图像的表示。您可以选择要使用的表示形式。

总结:

NSData * pngData = UIImagePNGRepresentation(originalImage);

将返回NSData对象中的图像表示形式,格式为PNG。

答案 1 :(得分:4)

当委托方法imagePickerController:didFinishPickingMediaWithInfo:调用UIImagePickerController时,您将获得所选照片的​​资产URL。

[info valueForKey:UIImagePickerControllerReferenceURL]

现在,此URL可用于访问ALAssetsLibrary中的资产。然后,您将需要该访问资产的ALAssetRepresentation。从这个ALAssetRepresentation我们可以得到该图像的UTI(http://developer.apple.com/library/ios/#DOCUMENTATION/FileManagement/Conceptual/understanding_utis/understand_utis_conc/understand_utis_conc.html

也许代码会让它更清晰:

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

正如UTI解释的那样,这应该是图像存储在照片库中的确定答案。

答案 2 :(得分:1)

在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 {

        }