简体   繁体   English

如何从使用相机拍摄的 UIImagePickerController 中获取图像名称

[英]How to get image name from UIImagePickerController taken with Camera

This below code is working perfectly fine for images picked from gallery.下面的代码非常适合从图库中挑选的图像。 But will not work if taken with Camera.但如果用相机拍摄将不起作用。 I tried to save image into storage and read again, but I was unable to do that.我试图将图像保存到存储器中并再次读取,但我无法做到这一点。 So could any one help me in this?那么有人可以帮助我吗? Thank you.谢谢你。

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {


    if let referenceUrl = info[UIImagePickerControllerReferenceURL] as? NSURL, image = info[UIImagePickerControllerOriginalImage] as? UIImage  {
            let phAsset = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl], options: nil).lastObject as! PHAsset
            PHImageManager.defaultManager().requestImageDataForAsset(phAsset, options: PHImageRequestOptions(), resultHandler: { (imagedata, dataUTI, orientation, info) in
                if info!.keys.contains(NSString(string: "PHImageFileURLKey")) {
                    let path = info![NSString(string: "PHImageFileURLKey")] as! NSURL
                    print("path q\(path)")

                    self.mImageUrl = path
                    self.mlocalPath = path.path
                    self.mImageExtension = path.pathExtension
                    self.mImageName = path.lastPathComponent!
                    print("mImageName q\(self.mImageName)")
                }

            })
    }

    dismissViewControllerAnimated(true, completion: nil)

}

Swift 5+斯威夫特 5+

As the previous answers sugested, the image is not stored in gallery yet and hence no imageName .正如前面的答案所暗示的那样,图像尚未存储在图库中,因此没有imageName You need to store it in gallery.您需要将其存储在图库中。 Use the below Helper class to save and get images from FileManager .使用下面的 Helper 类从FileManager保存和获取图像。

Thanks to this Answer感谢这个答案

class CameraImageManager {
    
    static let shared = CameraImageManager()

   public func saveImage(imageName: String, image: UIImage) {

        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

        let fileName = imageName
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        guard let data = image.jpegData(compressionQuality: 1) else { return }

        //Checks if file exists, removes it if so.
        if FileManager.default.fileExists(atPath: fileURL.path) {
            do {
                try FileManager.default.removeItem(atPath: fileURL.path)
                print("Removed old image")
            } catch let removeError {
                print("couldn't remove file at path", removeError)
            }

        }

        do {
            try data.write(to: fileURL)
        } catch let error {
            print("error saving file with error", error)
        }

    }

    public func getImagePathFromDiskWith(fileName: String) -> URL? {

        let documentDirectory = FileManager.SearchPathDirectory.documentDirectory

        let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
        let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)

        if let dirPath = paths.first {
            let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
            return imageUrl
        }

        return nil
    }

   public func loadImageFromDiskWith(fileName: String) -> UIImage? {

        let documentDirectory = FileManager.SearchPathDirectory.documentDirectory

        let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
        let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)

        if let dirPath = paths.first {
            let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
            let image = UIImage(contentsOfFile: imageUrl.path)
            return image

        }

        return nil
    }

}

Now, in your imagePickerController didFinishPickingMediaWithInfo callback function, this is how you can assign a name to an image and save it.现在,在您的imagePickerController didFinishPickingMediaWithInfo回调函数中,这就是您可以为图像分配名称并保存它的方法。

public func imagePickerController(_ picker: UIImagePickerController,
                                  didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
    guard let image = info[.editedImage] as? UIImage else { return }
    let imageName = "RDV_" + UUID().uuidString
    CameraImageManager.shared.saveImage(imageName: imageName, image: image)
    print("IMAGE NAME IS: ", imageName)
}

Hope It Helps.希望能帮助到你。

You can use a notification with addObserver like this您可以像这样使用带有 addObserver 的通知

ViewController A: where you want image to be changed, add this in viewDidLoad ViewController A: 在你想要改变图像的地方,在 viewDidLoad 中添加这个

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.methodOfImageChange(_:)), name:"ImageChanged", object: nil)

Add this method in ViewController A在 ViewController A 中添加此方法

func methodOfImageChange(notification: NSNotification){
    let appStatus = notification.userInfo as? Dictionary<String,AnyObject>   
    // appStatus contains your image in "image" key 
   }

Now in didFinishPickingMediaWithInfo add this现在在 didFinishPickingMediaWithInfo 添加这个

let dictionary: [String:AnyObject] = [
        "image" : (info[UIImagePickerControllerOriginalImage] as? UIImage)!,
        ]
    NSNotificationCenter.defaultCenter().postNotificationName("ImageChanged", object: self, userInfo: dictionary)

    picker .dismissViewControllerAnimated(true, completion: nil)

Hope this helps希望这可以帮助

The image isn't in the gallery yet, so I don't believe you have a name.图片还没有在图库中,所以我不相信你有名字。

In my app the flow (via navigation controller) is:在我的应用程序中,流程(通过导航控制器)是:

  • Selection VC (choice of Camera or Photo Library) ->选择 VC(选择相机或照片库)->
  • UIImagePickerController -> UIImagePickerController ->
  • Edit VC (with back navigation and action button for - among others - saving to Photo Library)编辑 VC(带有后退导航和操作按钮,用于保存到照片库)

If the user chooses Camera, they take a picture and the options are "Retake" or "Use Photo".如果用户选择相机,他们会拍照,选项是“重拍”或“使用照片”。 Is they choose "Use Photo", they are in the Edit VC.如果他们选择“使用照片”,他们就在编辑 VC 中。

If they then choose to go back to the Select VC, the image is nowhere to be found.如果他们随后选择返回到 Select VC,则无法找到该图像。

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

相关问题 如何上传从UIImagePickerController中获取的图像 - How to upload image that was taken from UIImagePickerController 异步加载从UIImagePickerController相机拍摄的照片 - Loading a photo taken from UIImagePickerController camera asynchronously 通过UIImagepickerController从Camera拾取图像并将其保存到ios中的相册后,获取图像名称 - Get image name after picking image from Camera through UIImagepickerController and saving it to photos album in ios 如何从相机拍摄图像以占据整个屏幕 - How to get an image taken from the camera to take up the entire screen 你如何从 UIImagePickerController 获取图像文件名? - How do you get image file name from UIImagePickerController? 如何将从UIImagePickerController中获取的图像保存为HEIF文件? - How to save image taken from UIImagePickerController as HEIF file? 如何从UIImagePickerController拍摄的照片和视频中获取日期? - How to get date from photos AND videos taken from UIImagePickerController? 相机的UIImagePickerController:获取包含位置数据的图像 - UIImagePickerController from camera: Get back image with location data 在Swift中获取图像名称UIImagePickerController - Get image name UIImagePickerController in Swift 如何确定图像是从库中还是从相机中获取的 - How to determine whether an image was taken from the library or from the camera
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM