iOS: UIImage size in bytes is different than actual image size

Viewed 135

I’m try to get the size in bytes of UIImage. The problem is that my actual image is of 5MB and when i get the size using

let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
let imgData = NSData(data: image.jpegData(compressionQuality: 1)!)
var imageSize: Int = imgData.count
print("actual size of image in KB: %f ", Double(imageSize) / 1000.0)   

I’m getting 2MB only. can anyone enlighten me on this please.

2 Answers

Doesn't this line recompress the image?

    let imgData = NSData(data: image.jpegData(compressionQuality: 1)!)

If so, I'd definitely expect the resulting image to be smaller than the original.

This worked for me instead of UIImage().jpegdata

  public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var asset: PHAsset!
    if #available(iOS 11.0, *) {
      asset = info[UIImagePickerControllerPHAsset] as? PHAsset
    } else {
      if let url = info[UIImagePickerControllerReferenceURL] as? URL {
        asset = PHAsset.fetchAssets(withALAssetURLs: [url], options: .none).firstObject!
      }
    }

    if #available(iOS 13, *) {
      PHImageManager.default().requestImageDataAndOrientation(for: asset, options: .none) { data, string, orien, info in
        let imgData = NSData(data:data!)
        var imageSize: Int = imgData.count
        print("actual size of image in KB: %f ", Double(imageSize) / 1024.0)
      }
    } else {
      PHImageManager.default().requestImageData(for: asset, options: .none) { data, string, orientation, info in
        let imgData = NSData(data:data!)
        var imageSize: Int = imgData.count
        print("actual size of image in KB: %f ", Double(imageSize) / 1024.0)
      }
    }
  }
Related