简体   繁体   中英

iOS Swift: UIImagePickerController HEIC to Jpg

I'm using a UIImagePickerController to pick images from the user's library.

Then I present these images aa 1/1 share ration in a fit content mode. It works very good when the images are jpg, but when they are HEIC they are stretched.

Is there a way to know if an image is Heic and then convert it in a jpg image?

This is my didFinishPickingMediaWithInfo

func imagePickerController(_ picker: UIImagePickerController,
                                   didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

            guard let type = info[.mediaType] as? String else { return }
            var mediaUrl: NSURL?
            var fileType: MediaFile.FileType
            switch type {
            case "public.image":
                mediaUrl = info[.imageURL] as? NSURL
                fileType = .image
            case "public.video":
                mediaUrl = info[.mediaURL] as? NSURL
                fileType = .video
            default:
                return
            }

            if let url = mediaUrl as URL? {
                model?.chooseMedia(url: url, type: fileType)
            }
        }

And this my code for the image view:

GeometryReader { proxy in
                if (self.model.image != nil) {
                    Image(uiImage: self.model.image!)
                        .resizable()
                        .scaledToFill()
                        .frame(width: proxy.size.width, height: proxy.size.width)
                        .aspectRatio(1/1, contentMode: .fit)
                        .clipped()
                        .animation(nil)
                    }
}

Instead of using the file url, you want to grab the image itself. If you really need the jpg representation, then you can get it by using:

if 
    let image: UIImage? = info?[.originalImage] as? UIImage,
    let data = image.jpegData(compressionQuality: 0.8) {
        //TADA: your image data can be used here
}

But it looks like you're using it within an image view which you could use the UIImage directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM