-1

I'm facing some issue to get image size in my code here is what I'm doing:

let imageData : NSData = UIImageJPEGRepresentation(images[0], 1) as! NSData 
let formatter = ByteCountFormatter() 
formatter.allowedUnits = .useKB 
formatter.countStyle = .binary 
let imageSize = formatter.string(fromByteCount: Int64(imageData.length))
print(imageSize)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
phadte viraj
  • 67
  • 2
  • 7
  • NSData *imageData = UIImageJPEGRepresentation(_imgBackground.image, 1); int imageSize = imageData.length/1024.0; try this – Ravi Panchal Apr 17 '18 at 11:39
  • What do you mean by image picker? Can you please give more detail? – Emre Önder Apr 17 '18 at 11:44
  • Im using UIPickerView to select image from my gallery and im setting it particular view , but there are memory contraints on it – phadte viraj Apr 17 '18 at 12:12
  • You shouldn't create an array of images. You should create an array with their URLs. No wonder you are having some memory issues – Leo Dabus Apr 17 '18 at 12:14
  • @Ravipanchal i have tried it, Im crossChecking size which im getting on my log with the actual size on my phone but its not matching – phadte viraj Apr 17 '18 at 12:15
  • `let data = UIImageJPEGRepresentation(image, 1.0)!; print(ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: ByteCountFormatter.CountStyle.file))` – TheTiger Apr 17 '18 at 12:17
  • Please see [this answer](https://stackoverflow.com/a/49878038/1140335) – TheTiger Apr 17 '18 at 12:25
  • .binary will do over there – phadte viraj Apr 17 '18 at 12:39
  • @LeoDabus I agree but Apple mentioned [this in doc](https://i.imgur.com/iMtNHNF.png) so I used `.file`. – TheTiger Apr 17 '18 at 12:43
  • @LeoDabus `.memory` is use for `binaryStyle` and `.file` is for `decimalStyle`. Shouldn't we need to show the size in decimals like `1.7 MB`? – TheTiger Apr 17 '18 at 12:50
  • if you are passing the Data count you should use `.memory` if you are passing the fileSize you should use `.file` – Leo Dabus Apr 17 '18 at 12:54
  • to use .file it would be something like this `if let url = info[UIImagePickerControllerImageURL] as? URL { do { if let fileSize = (try url.resourceValues(forKeys: [.fileSizeKey])).fileSize { print("fileSize", fileSize) let formatter = ByteCountFormatter() formatter.allowedUnits = .useKB formatter.countStyle = .file let imageSizeInKB = formatter.string(for: fileSize) ?? "" print("imageSizeInKB:",imageSizeInKB) } } catch { print(error)}}` – Leo Dabus Apr 17 '18 at 12:55
  • But when I test it with `.file` it prints `1.7 MB` and `.memory` also prints `1.7 MB`. I will change it to `.memory` but in which case it will give different result? – TheTiger Apr 17 '18 at 13:04
  • @TheTiger I don't know exactly in which circumstances it would make a difference. Note that you can also get `.totalFileSizeKey`, `.fileAllocatedSizeKey` and `.totalFileAllocatedSizeKey` which includes the metadata file size – Leo Dabus Apr 17 '18 at 13:11
  • @LeoDabus Okay, Thanks for your comments. I change it to `.memory`. – TheTiger Apr 17 '18 at 13:13

3 Answers3

1

Here You can get image size

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
            var Size = Float()
            var data = Data()
            btnCancel.isUserInteractionEnabled = true

            if let mediaType = info[UIImagePickerControllerMediaType] as? String {

                if mediaType  == "public.image" {
                    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
                        data = UIImageJPEGRepresentation(pickedImage, 1.0)!
                      //Here you get MB size
                        Size = Float(Double(data.count)/1024/1024)

                      //For Kb just remove single 1024 from size 

                      // I am checking 5 MB size here you check as you want
                        if Size <= 5.00{
                            // Here your image
                        }  
                    }
                }
                else
                if mediaType == "public.movie" {
                    let videoURL = info[UIImagePickerControllerMediaURL] as? URL
                    data = try! Data.init(contentsOf: videoURL!)
                    Size = Float(Double(data.count)/1024/1024)
                    if Size <= 5.00{
                        //your video here
                    }
                }
            }
            picker.dismiss(animated: true) {
                if Size > 5.0{
                    Utilities.showAlertView(title: "title", message: "message")
                }
            }
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            picker.dismiss(animated: true, completion: nil)
        }
Jitendra Modi
  • 2,344
  • 12
  • 34
0

You can simply check the size in KB by the following UIImage extension:

extension UIImage {
    func logImageSizeInKB(scale: CGFloat) -> (Int, Data) {
        let data = UIImageJPEGRepresentation(self, scale)!
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = ByteCountFormatter.Units.useKB
        formatter.countStyle = ByteCountFormatter.CountStyle.file
        let imageSize = formatter.string(fromByteCount: Int64(data.count))
        print("ImageSize(KB): \(imageSize)")

        return (Int(Int64(data.count) / 1024), data)
    }
}

Note:

Can use UIImagePNGRepresentation too for png image size. By the way PNG images are heavier than JPEG/ JPG.

Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36
0

Try this code, to get image size when getting an image from picker view.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        dismiss(animated: true, completion: nil);

        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        //get the size of image
        let imgData: NSData = NSData(data: UIImageJPEGRepresentation((chosenImage), 1)!)
        let imageSize: Int = imgData.length
        print("size of image in MB: %f ", Double(imageSize) / 1024.0/1024.0)
    }
AtulParmar
  • 4,358
  • 1
  • 24
  • 45