如何在iOS 4.0+中获取UIImage的大小(以字节为单位)?

11

我正试图从照片库或相机中选择一张图片。
委托方法:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo

给我UIImage对象。 我需要找到应用程序中图像的大小(以字节为单位)。

有没有办法获取图像的文件类型和大小(以字节为单位)?

非常感谢任何帮助。

提前致谢

4个回答

35

尝试下面的代码:

NSData *imageData = [[NSData alloc] initWithData:UIImageJPEGRepresentation((image), 1.0)];

int imageSize = imageData.length;
NSLog(@"SIZE OF IMAGE: %i ", imageSize);

2
在UIImageJPEGRepresentation中传递的压缩质量应该是多少?我看到这里有0.5,这会使我的计算大小比原始大小小,而1则会使其变大。 - R3D3vil
非常重要的是要知道在压缩图像时使用了哪种压缩率。我被告知,iOS 8相机的默认压缩率为92%,但这并不意味着您库中的所有图像都具有此压缩比,其中一些可能来自另一个相机或操作系统。 - kas-kad

17

我知道这是一个老问题,但是创建一个NSData对象只为了获取图像的字节大小可能是一项非常昂贵的操作。图像可能超过20Mb,为了获取第一个对象的大小而创建同样大小的对象...

我倾向于使用这个类别:

UIImage + CalculatedSize.h

#import <UIKit/UIKit.h>

@interface UIImage (CalculatedSize)

-(NSUInteger)calculatedSize;

@end

UIImage+CalculatedSize.m

#import "UIImage+CalculatedSize.h"

@implementation UIImage (CalculatedSize)

-(NSUInteger)calculatedSize
{    
    return CGImageGetHeight(self.CGImage) * CGImageGetBytesPerRow(self.CGImage);
}

@end

您只需导入 UIImage+CalculatedSize.h 并像这样使用:

NSLog (@"myImage size is: %u",myImage.calculatedSize);

或者,如果你想避免使用分类:

NSUInteger imgSize  = CGImageGetHeight(anImage.CGImage) * CGImageGetBytesPerRow(anImage.CGImage);

编辑:

当然,这种计算与JPEG/PNG压缩没有任何关系。它与底层的CGimage有关:

位图(或采样)图像是像素的矩形数组,每个像素表示源图像中的单个样本或数据点。

以这种方式检索到的大小为您提供了最坏情况的信息,而不会创建昂贵的附加对象。


1
此外,调用UIImageJPEGRepresentation本身会消耗大量内存和CPU资源。 - dokkaebi
1
但这样做能返回正确的图像尺寸吗?JPEG和PNG都是压缩格式。 - Legoless
这个并没有返回正确的大小,请查看https://dev59.com/EXM_5IYBdhLWcg3wn0vT#1296933。 - onmyway133

2

来自@fbrereto答案:

UIImage的基础数据可能会有所不同,因此对于同一张“图片”,其数据大小可能会有所不同。您可以使用UIImagePNGRepresentationUIImageJPEGRepresentation来获取它们的等效NSData构造,并检查其大小。

来自@Meet答案:

 UIImage *img = [UIImage imageNamed:@"sample.png"];
 NSData *imgData = UIImageJPEGRepresentation(img, 1.0); 
 NSLog(@"Size of Image(bytes):%d",[imgData length]);

0
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)editInfo{
   UIImage *image=[editInfo valueForKey:UIImagePickerControllerOriginalImage];
   NSURL *imageURL=[editInfo valueForKey:UIImagePickerControllerReferenceURL];
   __block long long realSize;

   ALAssetsLibraryAssetForURLResultBlock resultBlock=^(ALAsset *asset)
   {
      ALAssetRepresentation *representation=[asset defaultRepresentation];
      realSize=[representation size];
   };

   ALAssetsLibraryAccessFailureBlock failureBlock=^(NSError *error)
   {
      NSLog(@"%@", [error localizedDescription]);
   };

   if(imageURL)
   {
      ALAssetsLibrary *assetsLibrary=[[[ALAssetsLibrary alloc] init] autorelease];
      [assetsLibrary assetForURL:imageURL resultBlock:resultBlock failureBlock:failureBlock];
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接