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

huangapple go评论78阅读模式
英文:

How to load image from Photos after saving it via camera?

问题

I have saved my camera captured photo to Photos and then trying to access it. I am able to successfully save it using PHPhotoLibrary and once saved I get a path like this file:///var/mobile/Media/DCIM/100APPLE/IMG_0048.JPG. Now I need to load this path inside an UIImageView.

I tried the below code

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))`,但图像未显示。

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

```swift
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")

但它也无法显示图像。

英文:

I have saved my camera captured photo to Photos and then trying to access it. I am able to successfully save it using PHPhotoLibrary and once saved I get a path like this file:///var/mobile/Media/DCIM/100APPLE/IMG_0048.JPG. Now I need to load this path inside an UIImageView

I tried the below code

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

but my app crash saying

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"}}

I tried using kingfisher library but it does not load the image as well using imageView.kf.setImage(with: URL(fileURLWithPath: imageUrl)) but image is not getting displayed

Another way which I tried was using below code, I am extracting image name from the path and then sending to load function

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
    }

and then using

imageView.image = load(fileName: "IMG_0048.JPG") but it does not display the image as well

答案1

得分: 1

以下是您要翻译的内容:

"All of your approaches are wrong. They are requesting a local data using local url and your url is from Photos, which need to use PHPhotoLibrary.
I assume you are using UIImagePickerController to take a photo, you can use PHAsset to request image data

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.
        }
    }
}

As @JeremyP's answer, after save a photo, you should save the localId instead of fullSizeImageURL and use this code to retrieve the photo

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

All of your approaches are wrong. They are requesting a local data using local url and your url is from Photos, which need to use PHPhotoLibrary.
I assume you are using UIImagePickerController to take a photo, you can use PHAsset to request image data

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.
        }
    }
}

As @JeremyP's answer, after save a photo, you should save the localId instead of fullSizeImageURL and use this code to retrieve the photo

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)
        }
    }
}

huangapple
  • 本文由 发表于 2023年4月11日 14:49:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75983102.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定