I'm trying to get the length of a UIImage. Not the width or height of the image, but the size of the data.
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.
Swift 4 & 5:
extension UIImage {
var sizeInBytes: Int {
guard let cgImage = self.cgImage else {
// This won't work for CIImage-based UIImages
assertionFailure()
return 0
}
return cgImage.bytesPerRow * cgImage.height
}
}
I tried to get image size using
let imgData = image.jpegData(compressionQuality: 1.0)
but it gives less than the actual size of image. Then i tried to get size using PNG representation.
let imageData = image.pngData()
but it gives more byte counts than the actual image size.
The only thing that worked perfectly for me.
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)
}
}
}