iOS:如何获取图像尺寸而不打开它 [英] iOS: how to get image dimensions without opening it

查看:120
本文介绍了iOS:如何获取图像尺寸而不打开它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS应用中,我需要根据尺寸(宽度/高度)提供图像滤镜,在Google图片搜索中考虑类似于大,中,小的内容。在创建列表时打开每个图像并读取其尺寸将是非常高性能的。有没有办法在不打开图像的情况下获取此信息?

In an iOS app, I need to provide image filters based on their size (width/height), think of something similar to "Large, Medium, Small" in Google images search. Opening each image and reading its dimensions when creating the list would be very performance intensive. Is there a way to get this info without opening the image itself?

Damien DeVille根据他的建议回答了下面的问题,我现在使用以下代码:

Damien DeVille answered the question below, based on his suggestion, I am now using the following code:

NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
if (imageURL == nil)
    return;

CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((CFURLRef)imageURL, NULL);
if(imageSourceRef == NULL)
    return;

CFDictionaryRef props = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, NULL);    
CFRelease(imageSourceRef);

NSLog(@"%@", (NSDictionary *)props);

CFRelease(props);


推荐答案

您可以使用ImageIO实现这一目标。

You can use ImageIO to achieve that.

如果您有图像URL(或从文件路径创建一个带有NSURL上的+ fileURLWithPath的URL),则可以使用CGImageSourceCreateWithURL创建一个图像源(您必须桥接CFURLRef的URL。

If you have your image URL (or from a file path create a URL with +fileURLWithPath on NSURL) you can then create an image source with CGImageSourceCreateWithURL (you will have to bridge cast the URL to CFURLRef).

获得图像源后,您可以通过调用CGImageSourceCopyPropertiesAtIndex获取图像属性的CFDictionaryRef(您可以再次桥接转换为NSDictionary) 。你得到的是一个字典,其中有很多关于图像的属性,包括pixelHeight和pixelWidth。

Once you have the image source, you can get a CFDictionaryRef of properties of the image (that you can again bridge cast to NSDictionary) by calling CGImageSourceCopyPropertiesAtIndex. What you get is a dictionary with plenty of properties about the image including the pixelHeight and pixelWidth.

你可以传递0作为索引。该索引是因为某些图像可能具有各种嵌入图像(例如缩略图或gif中的多个帧)。

You can pass 0 as the index. The index is because some images might have various embedded images (such as a thumbnail, or multiple frame like in a gif).

请注意,通过使用图像源,完整图像不必加载到内存中,但您仍然可以访问其属性。

Note that by using an image source, the full image won't have to be loaded into memory but you will still be able to access its properties.

让您导入并将框架添加到项目中。

Make you you import and add the framework to your project.

这篇关于iOS:如何获取图像尺寸而不打开它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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