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

后端 未结 10 1973
说谎
说谎 2020-11-28 09:00

I\'m trying to get the length of a UIImage. Not the width or height of the image, but the size of the data.

相关标签:
10条回答
  • 2020-11-28 09:29

    Swift 3:

    let image = UIImage(named: "example.jpg")
    if let data = UIImageJPEGRepresentation(image, 1.0) {
        print("Size: \(data.count) bytes")
    }
    
    0 讨论(0)
  • 2020-11-28 09:29

    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.

    0 讨论(0)
  • 2020-11-28 09:31

    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.

    0 讨论(0)
  • 2020-11-28 09:39

    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.

    0 讨论(0)
  • 2020-11-28 09:41

    Example in Swift:

    let img: UIImage? = UIImage(named: "yolo.png")
    let imgData: NSData = UIImageJPEGRepresentation(img, 0)
    println("Size of Image: \(imgData.length) bytes")
    
    0 讨论(0)
  • 2020-11-28 09:45

    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);
    }
    
    0 讨论(0)
提交回复
热议问题