繁体   English   中英

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

[英]How to get Size of UIImage in Bytes in iOS 4.0+?

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

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

给我UIImage对象。 我需要为我的应用程序找到图像的大小(以bytesbytes

有什么办法可以获得图像的文件类型以及字节大小吗?

任何形式的帮助将受到高度赞赏。

提前致谢

请尝试以下代码:

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

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

我知道这是一个老问题但是创建一个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

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

在某种程度上,以这种方式检索的大小可以为您提供最坏情况的方案信息,而无需实际创建昂贵的附加对象。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM