如何在iOS 4.0 +中获取字节大小的UIImage?

我正在尝试从照片库或照相机中选取图像。
委托方法:

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

给我UIImage对象。 我需要为我的应用程序find图片的大小。

有什么办法可以得到图像的文件types,也有字节的大小?

任何forms的帮助将不胜感激。

提前致谢

试试下面的代码:

 NSData *imageData = [[NSData alloc] initWithData:UIImageJPEGRepresentation((image), 1.0)]; int imageSize = imageData.length; NSLog(@"SIZE OF IMAGE: %i ", imageSize); 

我知道这是一个老问题,但创build一个NSData对象只是为了获得图像的字节大小可能是一个非常昂贵的操作。 图像可以有超过20Mb,并创build相同大小的对象,以获得第一个的大小…

我倾向于使用这个类别:

的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 :

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

通过这种方式检索的大小可以为您提供最糟糕的场景信息,而无需实际创build昂贵的附加对象。

来自: @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]); 
 - (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]; } }