从NSData或UIImage中查找图像类型 [英] Finding image type from NSData or UIImage

查看:166
本文介绍了从NSData或UIImage中查找图像类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从第三方提供的网址加载图片。 URL上没有文件扩展名(或文件名)(因为它是一个模糊的URL)。我可以从中获取数据(以NSData的形式)并将其加载到UIImage中并显示它。

I am loading an image from a URL provided by a third-party. There is no file extension (or filename for that matter) on the URL (as it is an obscured URL). I can take the data from this (in the form of NSData) and load it into a UIImage and display it fine.

我想将此数据保存到文件中。但是,我不知道数据的格式是什么(PNG,JPG,BMP)?我认为它是JPG(因为它是来自网络的图像)但是有一种程序化的方法可以找到它吗?我查看了StackOverflow并在文档中找不到任何内容。

I want to persist this data to a file. However, I don't know what format the data is in (PNG, JPG, BMP)? I assume it is JPG (since it's an image from the web) but is there a programmatic way of finding out for sure? I've looked around StackOverflow and at the documentation and haven't been able to find anything.

TIA。

编辑:我真的需要文件扩展名吗?我将它持久化到外部存储(Amazon S3),但考虑到它总是在iOS或浏览器的上下文中使用(两者在没有扩展的情况下解释数据似乎都很好)也许这不是问题。

Do I really need the file extension? I'm persisting it to an external storage (Amazon S3) but considering that it will always be used in the context of iOS or a browser (both of whom seem fine in interpreting the data without an extension) perhaps this is a non-issue.

推荐答案

如果您有图像文件的NSData,那么您可以通过查看第一个字节来猜测内容类型:

If you have NSData for the image file, then you can guess at the content type by looking at the first byte:

+ (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];

    switch (c) {
    case 0xFF:
        return @"image/jpeg";
    case 0x89:
        return @"image/png";
    case 0x47:
        return @"image/gif";
    case 0x49:
    case 0x4D:
        return @"image/tiff";
    }
    return nil;
}

这篇关于从NSData或UIImage中查找图像类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆