【问题标题】:how to convert JPEG' UIImage to lossless NSData?如何将 JPEG UIImage 转换为无损 NSData?
【发布时间】:2026-01-04 16:00:01
【问题描述】:

UIImageJPEGRpresentation()函数可以将JPEG的UIImage转换成NSData,但是是无损的吗? 我想从系统相册中选择一个图像并将其转换为 NSData,有没有一些方法可以实现这个目标? 先谢谢了!

【问题讨论】:

    标签: ios uiimage jpeg nsdata


    【解决方案1】:

    要从设备中选择图像,您必须使用UIImagePickerController

    let picker = UIImagePickerController()
    

    将以下内容添加到您的viewDidLoad()

    picker.delegate = self
    picker.allowsEditing = false
    picker.sourceType = .photoLibrary    //You can also go with .camera
    

    为了打开选择器视图添加这个

     self.present(picker, animated: true, completion: nil)
    

    为选取器视图添加委托方法以获取选取的图像

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        // Convert image to NSData
        let data = UIImagePNGRepresentation(image) as NSData?   //Your image as NSData
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
    

    *注意 不要忘记将Privacy - Photo Library Usage Description 添加到您的Info.plist 文件和UIImagePickerControllerDelegate, UINavigationControllerDelegate

    【讨论】:

      【解决方案2】:

      虽然 UIImageJPEGRpresentation() 将质量值作为第二个参数,但它始终是有损的!

      改用 UIImagePNGRepresentation()。

      【讨论】:

      • UIImagePNGRepresentation()的函数会改变图像的格式,我需要存储JPEG图像数据的NSData,因为我想在下一步从JPEG图像中获取DCT系数。