-1

In my application, I'm using YPImagepicker for selecting images from library and camera. I want to know image size in MB after selecting the pictures or capturing a photo. Task is to convert the images into data and send to backend via REST API. As of now we are limiting images into 5. So I want to see the size of every images if it is more than 1 Mb need to compress into 1mb.

let imgData = NSData(data: image.jpegData(compressionQuality: 1)!)
var imageSize: Int = imgData.count
print("actual size of image in KB: %f ", Double(imageSize) / 1024.0 / 1024.0)

the above sample I have used to check the size of the image but I'm not seeing the correct file size. For eg, I'm capturing one photo through app and it is getting saved in album when I check the image size it shows 3.4 MB in photo detail but in code I'm not getting the same size. What is best way to achieve this?

Prabhu
  • 157
  • 7
  • 1
    You don't need to convert to NSData, just do `var imageSize: Int = image.jpegData(compressionQuality: 1).count`. And it is the right way to calculate the size. How different it is from the real size? Can you bring the actual example? – timbre timbre Jan 24 '23 at 14:31
  • 1
    Why are you reposting [the same question](https://stackoverflow.com/questions/75184671/get-image-size-in-swift) without adding any new information? – Joakim Danielson Jan 24 '23 at 14:42
  • Quick searching .... this looks like what you want: https://stackoverflow.com/a/63270234/6257435 – DonMag Jan 24 '23 at 14:51

1 Answers1

0

Apple doesn’t use JPEG for storing images in your iOS library. They use a proprietary file format with its own lossy compression.

The two file formats will yield different file sizes.

When you load an image from the user’s image library and convert it to JPEG data, it gets re-compressed using JPEG compression with the image quality value you specify. A compressionQuality value of 1.0 will create an image file with the best image quality but the largest file size. That is why your results are bigger than the files from the user’s image library. Try a lower compressionQuality value.

Duncan C
  • 128,072
  • 22
  • 173
  • 272