简体   繁体   English

iOS UIImagePickerController如何从相机拍摄图像后立即保存图像

[英]iOS UIImagePickerController how to save image right after taking image from camera

I am facing difficulties storing an image taken from the camera when using UIImagePickerController and getting its URL. 使用UIImagePickerController并获取其URL时,我在存储从相机拍摄的图像时遇到困难。

Checking the logs, I think it's because the taken image has no saved path on phone? 检查日志,我认为是因为所拍摄的图像在电话上没有保存的路径?

let imageUrl          = info[UIImagePickerControllerImageURL] as? NSURL // logs show nil here
...
let localPath         = photoURL.appendingPathComponent(imageName!) // crashes here due to forced unwrap of imageName (nil)

I wonder how I can fix this? 我不知道该如何解决? I have consulted other answers but none of them work (deprecated libraries or other issues). 我已经咨询了其他答案,但是它们都不起作用(不建议使用的库或其他问题)。

More complete code: 更完整的代码:

func openCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let imagePickerController = UIImagePickerController()
            imagePickerController.delegate = self
            imagePickerController.sourceType = .camera;
            imagePickerController.allowsEditing = false
            present(imagePickerController, animated: true, completion: nil)
        }
    }


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            fatalError("error message")
        }

        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let imageUrl          = info[UIImagePickerControllerImageURL] as? NSURL // logs show nil here
        let imageName         = imageUrl?.lastPathComponent
        let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let photoURL          = NSURL(fileURLWithPath: documentDirectory)
        let localPath         = photoURL.appendingPathComponent(imageName!) // crashes here due to forced unwrap of imageName (nil)

        if !FileManager.default.fileExists(atPath: localPath!.path) {
            do {
                try UIImageJPEGRepresentation(image, 1.0)?.write(to: localPath!)
                print("file saved")
            }catch {
                print("error saving file")
            }
        }
        else {
            print("file already exists")
        }

        ...
        dismiss(animated: true, completion: nil)
    }

There is very easy function for this: 有一个非常简单的功能:

UIImageWriteToSavedPhotosAlbum(chosenImage, nil, nil, nil)

But I've also created helper class to deal with this. 但是我也创建了帮助程序类来解决这个问题。 Thanks to this helper you can save photo in specified album 多亏了这个助手,您可以将照片保存在指定的相册中

import Foundation
import Photos

final class PhotoAlbumHelper: NSObject {

    static let albumName = "AppAlbum"
    static let shared = PhotoAlbumHelper()

    var assetCollection: PHAssetCollection?
    var failedPhotos = [UIImage]()

    func fetchAssetCollectionForAlbum() -> PHAssetCollection? {
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "title = %@", PhotoAlbumHelper.albumName)
        let collections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

        if let collection = collections.firstObject {
            return collection
        }
        return nil
    }

    func createAlbum() {
        PHPhotoLibrary.shared().performChanges({
            PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: PhotoAlbumHelper.albumName) // create an asset collection with the album name
        }) { [weak self] success, error in
            if success {
                guard let `self` = self else { return }
                self.assetCollection = self.fetchAssetCollectionForAlbum()
                while self.failedPhotos.count > 0 {
                    self.saveImage(self.failedPhotos.removeFirst())
                }
            } else {
                print(error)
            }
        }
    }

    func saveImage(_ image: UIImage) {
        assetCollection = fetchAssetCollectionForAlbum()
        if assetCollection == nil {
            failedPhotos.append(image)
            createAlbum()
            return
        }
        guard let album = assetCollection else { return }
        PHPhotoLibrary.shared().performChanges({
            let creationRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            guard let addAssetRequest = PHAssetCollectionChangeRequest(for: album) else { return }
            let index = IndexSet(integer: 0)
            addAssetRequest.insertAssets([creationRequest.placeholderForCreatedAsset!] as NSArray, at: index)
        }, completionHandler: { success, error in
            if !success {
                print(error)
            }
        })
    }
}

According to documentation : 根据文件:

A dictionary containing the original image and the edited image, if an image was picked; 包含原始图像和编辑图像(如果已选择图像)的词典; or a filesystem URL for the movie, if a movie was picked. 或电影的文件系统URL(如果已选择电影)。 The dictionary also contains any relevant editing information. 该词典还包含任何相关的编辑信息。 The keys for this dictionary are listed in Editing Information Keys. 该词典的键在“编辑信息键”中列出。

Link to Documentation 链接到文档

You cannot get the URL ( or you shouldn't ). 您无法获取URL(或不应获取)。 But you can have the image itself ( either in UIImagePickerControllerEditedImage or in UIImagePickerControllerOriginalImage . 但是您可以拥有图像本身(在UIImagePickerControllerEditedImageUIImagePickerControllerOriginalImage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从UIImagepickercontroller中选择后如何保存图像 - How to save image after selecting from UIImagepickercontroller iOS 7 UIImagePickerController相机无图像 - iOS 7 UIImagePickerController Camera No Image 通过UIImagepickerController从Camera拾取图像并将其保存到ios中的相册后,获取图像名称 - Get image name after picking image from Camera through UIImagepickerController and saving it to photos album in ios 相机拍摄后如何将图像保存到应用程序的内部存储器 - How to save image to internal memory of app after taking it by camera 从UIImagePickerController捕获图像后,相机显示黑色图像 - Camera showing black image after capturing image from UIImagePickerController iOS从UIImagePickerController选择图像保存gif图像 - IOS save gif image from UIImagePickerController selected image 如何保存从Swift中的UIImagePickerController中拾取的图像? - How to save an image picked from a UIImagePickerController in Swift? 如何将图像从UIImagePickerController保存到应用程序文件夹? - How to Save Image to Application Folder from UIImagePickerController? iOS:使用叠加层裁剪从UIImagePickerController摄像头抓取的静止图像 - iOS: Cropping a still image grabbed from a UIImagePickerController camera with overlay iOS 7 UIImagePickerController相机覆盖静态图像 - iOS 7 UIImagePickerController Camera Covered with Static image
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM