如何知道这张图片是jpg还是png(iPhone)

5

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

我需要将其转换为NSData。但是,我需要知道这张图片是使用UIImageJPEGRepresentation还是UIImagePNGRepresentation,以便我能够进行转换。

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

10

您不需要了解或关心相机胶卷中图像的内部表示方式。您提到的方法UIImageJPEGRepresentationUIImagePNGRepresentation会返回相机胶卷图像的表示。由您决定使用哪种表示。

总结:

NSData * pngData = UIImagePNGRepresentation(originalImage);

这将返回一个以PNG格式表示的NSData对象,其中包含图像。


7
有时候你需要注意,因为如果你从JPEG图像创建UIImageJPEGRepresentation,你可能会压缩已经被压缩过的图像(失去质量并增加处理时间)。例如,你可能需要将选定的图像进一步处理为仅接受JPEG格式的库。 - Vilém Kurz

4
当UIImagePickerController的委托方法imagePickerController:didFinishPickingMediaWithInfo:被调用时,您将获得所选照片的资产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的解释,这应该是如何将图像存储在照片库中的确定答案。

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 {

        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接