如何转换JPEG' UIImage无损NSData?

时间:2017-06-20 14:50:01

标签: ios uiimage jpeg nsdata

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

2 个答案:

答案 0 :(得分:0)

要从设备中挑选图片,您必须使用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

答案 1 :(得分:0)

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

改为使用UIImagePNGRepresentation()。