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

后端 未结 4 1111
北恋
北恋 2021-02-08 08:01

I am trying to pick an image from the photo library or from the camera.
The delegate method:

- (void)imagePickerController:(UIImagePickerController *)picker d         


        
4条回答
  •  情深已故
    2021-02-08 08:24

    I know this is an old question but creating a NSData object just to get the byte-size of an image can be a really expensive operation. Image can have over 20Mb and creating equally sized object just to get the size of the first one...

    I tend to use this category:

    UIImage+CalculatedSize.h

    #import 
    
    @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
    

    You simply import the UIImage+CalculatedSize.h and use it like this:

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

    Or, if you want to avoid using categories:

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

    EDIT:

    This calculation of course has nothing to do with JPEG/PNG compression. It relates to underlaying CGimage:

    A bitmap (or sampled) image is a rectangular array of pixels, with each pixel representing a single sample or data point in a source image.

    In a way a size retrieved this way gives you a worst-case scenario information without actually creating an expensive additional object.

提交回复
热议问题