如何识别 NSData 的图像格式?
如果我得到一个 NSData,我知道它是图像的数据。但我不知道它是什么格式。 那么如何识别图片格式是Jpeg还是PNG呢?
PS:iOS
If I get a NSData which I know it's a image's data.But I don't know what format it is.
So how can I identify which image format is it?Jpeg or PNG?
PS:iOS
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我使用 Mats answer 在 NSData 上构建了一个简单的类别,它根据前 4 个字节告诉我其内容是 JPEG 还是 PNG:
然后,只需执行以下操作:
I used Mats answer to build a simple category on NSData which tells me if its content is JPEG or PNG based on its first 4 bytes:
And then, simply do a :
您可以查看第一个字节并进行猜测。互联网上有许多幻数列表,例如 http: //www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html。
You could look at the first bytes and make a guess. There are many lists of magic numbers available on the internet, e.g. http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html.
这是 @aouche 答案的 Swift 版本:
Here's a Swift version of the @apouche's answer:
您可以从中创建一个图像,然后询问 NSImage 它是什么格式吗?
您可以使用 -initWithData 创建 NSImage,有关更多信息,请参阅 http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSImage_Class/Reference/Reference.html
Can you create an image from that and then just ask that NSImage what format it is?
You can use -initWithData to create the NSImage, for more, see http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSImage_Class/Reference/Reference.html
您可以创建 CGImageSourceRef 然后询问其图像类型
You can create CGImageSourceRef and then ask it for image type
如果你使用UIImage imageWithData,你不需要知道数据是png还是jpg。
If you use UIImage imageWithData, you don't need to know if the data is png or jpg.