如何通过相机保存照片后加载图像?



我已将相机拍摄的照片保存到照片中,然后试图访问它。我能够使用phphotollibrary成功保存它,一旦保存,我得到这样的路径file:///var/mobile/Media/DCIM/100APPLE/IMG_0048.JPG。现在我需要将这个路径加载到UIImageView

中我试过下面的代码

let data = try! Data(contentsOf: URL(fileURLWithPath: "file:///var/mobile/Media/DCIM/100APPLE/IMG_0048.JPG"))
let image = UIImage(data: data)
imageView.image = image

但是我的应用程序崩溃了,说

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=260 "The file “IMG_0048.JPG” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/file:/var/mobile/Media/DCIM/100APPLE/IMG_0048.JPG, NSUnderlyingError=0x280c545a0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

我尝试使用kingfisher库,但它没有加载图像以及使用imageView.kf.setImage(with: URL(fileURLWithPath: imageUrl)),但图像没有显示

我尝试的另一种方法是使用下面的代码,我从路径中提取图像名称,然后发送到加载函数

var documentsUrl: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}

private func load(fileName: String) -> UIImage? {
let fileURL = documentsUrl.appendingPathComponent(fileName)
do {
let imageData = try Data(contentsOf: fileURL)
return UIImage(data: imageData)
} catch {
print("Error loading image : (error)")
}
return nil
}

,然后使用

imageView.image = load(fileName: "IMG_0048.JPG"),但它不显示图像

你所有的方法都是错误的。他们正在使用本地url请求本地数据,而您的url来自Photos,需要使用PHPhotoLibrary。我假设您正在使用UIImagePickerController拍照,您可以使用PHAsset请求图像数据

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let phAsset = info[.phAsset] as! PHAsset
PHPhotoLibrary.requestAuthorization { status in
if status == .authorized {
let imageManager = PHImageManager.default()
imageManager.requestImageData(for: phAsset, options: nil) { data, _, _, _ in
let image = UIImage(data: data!)
// Your image
}
} else {
// Access to the photo library is not authorized.
}
}
}

作为@JeremyP的回答,保存照片后,您应该保存localId而不是fullSizeImageURL,并使用此代码检索照片

func getPhotoInLibrary(localIdentifiers: String, completion: @escaping (UIImage?) -> Void) {
let result = PHAsset.fetchAssets(withLocalIdentifiers: [localId], options: nil)
guard let asset = result.firstObject else {
completion(nil)
return
}
PHImageManager.default().requestImageData(for: asset, options: nil) { data, _, _, _ in
if let data = data {
let image = UIImage(data: data)
completion(image)
} else {
completion(nil)
}
}
}

相关内容

  • 没有找到相关文章

最新更新