I have implement function for upload image but before upload I will preview image to user.
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult])
But suddenly I select image to preview, memory usage will super high change from 30mb to 480mb. It was happened after I set image to uiview. memory will depend on image size if big size my memory will get high too.
Making a small edit, to correct the answer, as in the question title you are asking for
UIImagePickerControllerbut in the question text a delegate method fromPHPickerViewControlleris referenced. Both of these controllers are provided by Apple and are dealing with image picking from the photo library andPHPickerViewControlleris the newer one available from iOS 14+, replacing the oldUIImagePickerControllerthat is to be used on older iOS versions.The provided solution could be used on both of them:
This is because i assume you take the result from the picker in
UIImageand set it to theUIImageView.UIImages could have a really big memory usage. For example if the picked image is 12MP (3024 x 4032 = 12 192 768), as the OS createsUIImageinstance for it, for each of the 12192768 pixels from the photo, 4 bytes are used in memory - one for alpha, one for red, one for green and one for the blue component.This means that in the phone memory, 12192768 * 4 = 48 771 072 bytes (48 mb) will be used. Its worth pointing out that this size is not the same as the one that the image is using when its on your disk drive, as when it is stored there its usually compressed with some algorithm like JPG or PNG.
I hope this gives you an insight on what the issue is.
One more efficient way to handle this is to get the picked image as
URLfrom the disk without instantiatingUIImageat all, and then from it, load a shrunken down representation from it into aUIImage, just for presentation to the user on its small phone screen, while uploading the original image. In some cases you might even decide to use the shrunken down image as it might be enough for your use case.Here's how you might do that in your
picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult])fromUIImagePickerControllerDelegate:where
URL's.asSmallImageis defined as:Where
cgImage.isPNGis defined as: