如何获得cocoa的形象作者

我不明白为什么metaDic总是空的。 有一个代码。

CFDataRef dataRef = CGDataProviderCopyData(CGImageGetDataProvider(img.CGImage)); //(UIImage *img) CGImageSourceRef mySourceRef = CGImageSourceCreateWithData(dataRef, NULL); NSDictionary *metaDic = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex(mySourceRef,0,NULL); NSDictionary *tiffDic = (NSDictionary *)[metaDic objectForKey:(NSString *)kCGImagePropertyTIFFDictionary]; NSString *AuthorName = [tiffDic objectForKey:(NSString *)kCGImagePropertyTIFFArtist]; 

我做了一些变体获取图片。 在这里我发现了

获取图片信息的一种方法 – 我需要从网站上获得它,并在那里得到:

  // NSURL *UrlPath - path of picture image.jpg from web site NSData *dataImg = [NSData dataWithContentsOfURL:UrlPath]; CGImageSourceRef mySource = CGImageSourceCreateWithData((CFDataRef)dataImg, NULL); NSDictionary *metaDic = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex(mySource,0,NULL); NSDictionary *tiffDic = [metaDic objectForKey:(NSString *)kCGImagePropertyTIFFDictionary]; /// Log of tiffDic tiffDic = { Artist =( "mr. Smith" ); } 

另一种方式 – 从NSBoudle mainBundle读取图片:

  // NSURL *NSBundleUrl - - path of the same picture image.jpg from [[NSBundle mainBundle] CGImageSourceRef mySource = CGImageSourceCreateWithURL( (CFURLRef) NSBundleUrl, NULL); NSDictionary *metaDic = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex(mySource,0,NULL); NSDictionary *tiffDic = [metaDic objectForKey:(NSString *)kCGImagePropertyTIFFDictionary]; /// Log of tiffDic tiffDic = { Artist = "mr. Smith"; } 

为什么当图片数据来自网站的时候,它被当作艺术家名字的数组呢?

你的数据path如下所示:

 UIImage -> CGImage -> CGDataProvider -> CGImageSource 

这是清理元数据图像的第三步。 CGDataProviders是一种“较旧”的机制,用于将数据导入“ 有限function ”的Quartz中,也就是说,它们不支持元数据。

尝试这样的事情,而不是:

 NSData* jpegData = UIImageJPEGRepresentation(image,1.0); CFDataRef dataRef = (__bridge CFDataRef)jpegData; CGImageSourceRef source = CGImageSourceCreateWithData(dataRef, NULL); 

数据path:

 UIImage -> NS/CFData -> CGImageSource 

这将保留元数据。

如果你使用UIImage作为你的出发点,你可能没有太多的运气来获取authorName。 UIImage去掉了许多可能伴随原始图像源的元数据(TiffDict似乎只是orientation到了orientation标签)。 你真的希望从源代码中读取“未解释的”数据,并在不读取图像数据的情况下提取元数据(这是使用CGImageSourceRef的好处之一)。

我在github上有一个testing项目 ,比较从各种来源提取图像元数据的方法 – 文件系统,networkingURL,资产库,相机,也许你应该看看。

更新 Peter指出(和我的项目显示) – 你不应该使用UIImage,而是原始的数据源。 在你的情况下,它是一个文件系统源,如下所示:

  NSString* path = @"/path/to/resource"; NSData *data = [NSData dataWithContentsOfFile:path]; CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); 

或者更好(正如Peter指出的那样),您可以使用CGImageSourceCreateWithURL并跳过该NSData步骤。

CGImage的数据提供者提供原始像素,而不是PNG或TIFF或包含元数据的其他外部格式数据。 因此,没有属性可以得到。

我不会惊讶,如果这个来源甚至不能给你一个形象,因为它无法知道什么像素格式来解释数据。

您需要使用从中获取原始图像的URL或数据创build图像源,而不是该图像的像素数据。 理想情况下,您应该先创build图像源,然后从图像源创build图像及其属性。