I\'m trying to get the length of a UIImage
. Not the width or height of the image, but the size of the data.
Swift 3:
let image = UIImage(named: "example.jpg")
if let data = UIImageJPEGRepresentation(image, 1.0) {
print("Size: \(data.count) bytes")
}
SWIFT 4+
let imgData = image?.jpegData(compressionQuality: 1.0)
debugPrint("Size of Image: \(imgData!.count) bytes")
you can use this trick to find out image size.
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.
If needed in human readable form we can use ByteCountFormatter
if let data = UIImageJPEGRepresentation(image, 1.0) {
let fileSizeStr = ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: ByteCountFormatter.CountStyle.memory)
print(fileSizeStr)
}
Where Int64(data.count)
is what you need in numeric format.
Example in Swift:
let img: UIImage? = UIImage(named: "yolo.png")
let imgData: NSData = UIImageJPEGRepresentation(img, 0)
println("Size of Image: \(imgData.length) bytes")
This following is the fastest, cleanest, most general, and least error-prone way to get the answer. In a category 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;
}
Or if you only want the actual bitmap and not the UIImage instance container, then it is truly as simple as this:
- (size_t) memorySize
{
return CGImageGetHeight(self.CGImage) * CGImageGetBytesPerRow(self.CGImage);
}