获取UIImage的大小(字节长度)而不是高度和宽度

Kev*_*vin 58 iphone uiimage

我想要得到一个长度UIImage.不是图像的宽度或高度,而是数据的大小.

Mee*_*eet 72

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

  • 而不是0应该放1.0; 它是原始图像的质量. (25认同)
  • 如果希望看到图像占用多少内存,为什么要获得它的压缩大小?通过使用UIImageJPEGRepresentation,您将创建一个占用空间并复制位的新图像; 如果您不希望消耗更多内存或者因为性能受到挤压,请不要这样做. (4认同)

fbr*_*eto 34

a的基础数据UIImage可以变化,因此对于相同的"图像",可以具有不同大小的数据.你可以做的一件事是使用UIImagePNGRepresentationUIImageJPEGRepresentation得到两者的等效NSData结构,然后检查它的大小.

  • UIImageJPEGRepresentation和UIImagePNGRepresentation将不会返回原始大小 (2认同)

mah*_*udz 17

使用UIImage的CGImage属性.然后使用CGImageGetBytesPerRow*
CGImageGetHeight 的组合,添加sizeof UIImage,你应该在实际大小的几个字节内.

这将返回未压缩的图像大小,如果你想将它用于malloc以便为位图操作做准备(假设RGB字节格式为3字节,Alpha格式为1字节):

int height = image.size.height,
    width = image.size.width;
int bytesPerRow = 4*width;
if (bytesPerRow % 16)
    bytesPerRow = ((bytesPerRow / 16) + 1) * 16;
int dataSize = height*bytesPerRow;
Run Code Online (Sandbox Code Playgroud)

  • 这里有几个问题; (1)`image.size.height`和`image.size.width`会给你CG单位的大小,而不一定是像素.如果`.scale`属性不是1,那么你将得到错误的答案.(2)您假设每个像素有4个字节,这对于RGBA图像是正确的,但对于灰度图像则不然. (3认同)

Dar*_*ngs 13

- (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];
   }
}
Run Code Online (Sandbox Code Playgroud)


Kin*_*ard 7

Swift中的示例:

let img: UIImage? = UIImage(named: "yolo.png")
let imgData: NSData = UIImageJPEGRepresentation(img, 0)
println("Size of Image: \(imgData.length) bytes")
Run Code Online (Sandbox Code Playgroud)


Tod*_*man 6

以下是获得答案的最快、最干净、最通用且最不容易出错的方法。在一个类别中UIImage+MemorySize

#import <objc/runtime.h>

- (size_t) memorySize
{
  CGImageRef image = self.CGImage;
  size_t instanceSize = class_getInstanceSize(self.class);
  size_t pixmapSize = CGImageGetHeight(image) * CGImageGetBytesPerRow(image);
  size_t totalSize = instanceSize + pixmapSize;
  return totalSize;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想要实际的位图而不是 UIImage 实例容器,那么它确实如此简单:

- (size_t) memorySize
{
  return CGImageGetHeight(self.CGImage) * CGImageGetBytesPerRow(self.CGImage);
}
Run Code Online (Sandbox Code Playgroud)