教你获取图片的尺寸和文件大小

有些时候我们会有这样的一些需求:需要获得一张图片的具体尺寸和所占的存储空间,这张图片可能来自网络、本地,也可能是在内存当中的 UIImage 对象。

基本思路:图片文件的本质是一些二进制数据,他们按照一定的规则存储在磁盘或内存当中,我们只需要在相应的位置取出我们需要的数据即可。不同格式的图片存储方式不同,数据所在的位置也不同,所幸的是前人已经帮我们做好了封装,我们只需要调用相关 API 即可。针对图片文件的大小,我们还可以通过计算数据的长度的方式来计算。

网络图片和本地图片

对于计算机系统而言,本地和网络都是计算机系统外部某个位置,所以这两种存储方式的方法是一致的。

图片的尺寸

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//需导入头文件#import <ImageIO/ImageIO.h>

- (CGSize)getImageSizeWithURL:(NSURL *)url
{
NSURL * mUrl = nil;
if ([url isKindOfClass:[NSURL class]]) {
mUrl = url;
}
if (!mUrl) {
return CGSizeZero;
}

CGFloat width = 0, height = 0;
CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((CFURLRef)mUrl, NULL);
if (imageSourceRef) {
CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, NULL);
if (imageProperties != NULL) {
CFNumberRef widthNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
if (widthNumberRef != NULL) {
CFNumberGetValue(widthNumberRef, kCFNumberFloat64Type, &width);
}
CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
if (heightNumberRef != NULL) {
CFNumberGetValue(heightNumberRef, kCFNumberFloat64Type, &height);
}
CFRelease(imageProperties);
}
CFRelease(imageSourceRef);
}
return CGSizeMake(width, height);
}

图片大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//需导入头文件#import <ImageIO/ImageIO.h>

- (CGFloat)getImageFileSizeWithURL:(NSURL *)url
{
NSURL *mUrl = nil;
if ([url isKindOfClass:[NSURL class]]) {
mUrl = url;
}
if (!mUrl) {
return 0.0f;
}

CGFloat fileSize = 0;
CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((CFURLRef)mUrl, NULL);
if (imageSourceRef) {
CFDictionaryRef imageProperties = CGImageSourceCopyProperties(imageSourceRef, NULL);
if (imageProperties != NULL) {
CFNumberRef fileSizeNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyFileSize);
if (fileSizeNumberRef != NULL) {
CFNumberGetValue(fileSizeNumberRef, kCFNumberFloat64Type, &fileSize);
}
CFRelease(imageProperties);
}
CFRelease(imageSourceRef);
}
return fileSize;
}

内存当中的 UIImage 对象

图片尺寸

1
2
UIImage *tempImage = [UIImage imageNamed:@"paperPlane"];
NSLog(@"imageSize:%f,%f",tempImage.size.width,tempImage.size.height);

图片大小

1
2
3
UIImage *tempImage = [UIImage imageNamed:@"paperPlane"];
NSData *imageData = UIImagePNGRepresentation(tempImage);
NSLog(@"imageFileSize:%ld",(long)imageData.length);

其他
网络和本地图片也可以通过 IO 读入计算,但需要拿到图片的全部数据,不推荐。