Get size of a UIImage (bytes length) not height and width

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

The underlying data of a UIImage can vary, so for the same "image" one can have varying sizes of data. One thing you can do is use UIImagePNGRepresentation or UIImageJPEGRepresentation to get the equivalent NSData constructs for either, then check the size of that.


Use the CGImage property of UIImage. Then using a combination of CGImageGetBytesPerRow *
CGImageGetHeight, add in the sizeof UIImage, you should be within a few bytes of the actual size.

This will return the size of the image, uncompressed, if you want to use it for purposes such as malloc in preparation for bitmap manipulation (assuming a 4 byte pixel format of 3 bytes for RGB and 1 for Alpha):

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;

- (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];
   }
}

Tags:

Iphone

Uiimage