【发布时间】:2026-01-04 16:00:01
【问题描述】:
UIImageJPEGRpresentation()函数可以将JPEG的UIImage转换成NSData,但是是无损的吗? 我想从系统相册中选择一个图像并将其转换为 NSData,有没有一些方法可以实现这个目标? 先谢谢了!
【问题讨论】:
UIImageJPEGRpresentation()函数可以将JPEG的UIImage转换成NSData,但是是无损的吗? 我想从系统相册中选择一个图像并将其转换为 NSData,有没有一些方法可以实现这个目标? 先谢谢了!
【问题讨论】:
要从设备中选择图像,您必须使用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
【讨论】:
虽然 UIImageJPEGRpresentation() 将质量值作为第二个参数,但它始终是有损的!
改用 UIImagePNGRepresentation()。
【讨论】: