ios 读取本地图片到NSdata
时间: 2024-09-15 18:06:25 浏览: 69
在iOS中,读取本地图片并将其转换为NSData对象通常通过UIImagePickerController或UIImage类来完成。以下是基本步骤:
1. 首先,你需要导入相关的框架:
```swift
import UIKit
```
2. 使用UIImagePickerController让用户选择图片:
```swift
let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self // 确保你的视图控制器实现了UIImagePickerControllerDelegate和UINavigationControllerDelegate协议
if let sourceViewController = UIApplication.shared.keyWindow?.rootViewController {
sourceViewController.present(imagePickerController, animated: true, completion: nil)
}
```
3. 当用户选择图片后,在`UIImagePickerControllerDelegate`方法里获取UIImage对象,并将其转化为NSData:
```swift
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
do {
let imageData = try selectedImage.jpegData(compressionQuality: 0.8) // 或者pngData等,根据需要选择压缩质量
// imageData就是你想要的NSData对象了
} catch {
print("Failed to convert image to data: \(error)")
}
dismiss(animated: true, completion: nil)
}
```
4. 最后记得处理取消选择或关闭相机的情况。
阅读全文