Getting Url of Uiimage Selected from Uiimagepickercontroller

Getting URL of UIImage selected from UIImagePickerController

Okay, I've solved the issue.

All you have to do is simply grab the image (info[UIImagePickerControllerOriginalImage] as UIImage) and save to the given directory. If you need to save only 1 picture it works great. The code id below.

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL
let imageName = imageURL.path!.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String
let localPath = documentDirectory.stringByAppendingPathComponent(imageName)

let image = info[UIImagePickerControllerOriginalImage] as UIImage
let data = UIImagePNGRepresentation(image)
data.writeToFile(localPath, atomically: true)

let imageData = NSData(contentsOfFile: localPath)!
let photoURL = NSURL(fileURLWithPath: localPath)
let imageWithData = UIImage(data: imageData)!

picker.dismissViewControllerAnimated(true, completion: nil)

}

Getting URL of UIImage from UIImagePickerController

Apple has changed something in their NSString and NSURL library in their latest release (iOS 9), but those methods are available from iOS 4. You can check the related Apple Forum Post for more details.

For fixing this error, you need to change the code like:

Swift 2:

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!)
{
let imageUrl = editingInfo[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.URLByAppendingPathComponent(imageName!)
let image = editingInfo[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)

data!.writeToFile(localPath.absoluteString, atomically: true)

self.dismissViewControllerAnimated(true, completion: nil);
}

Swift 3:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)

do
{
try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
}
catch
{
// Catch exception here and act accordingly
}

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

Reference:

  1. lastPathComponent
  2. URLByAppendingPathComponent:

Get Image URL of photo with UIImagePickerControllerDelegate

Yes, but with another key:

info[UIImagePickerController.InfoKey.originalImage] as? UIImage

or

info[UIImagePickerController.InfoKey.editedImage] as? UIImage

Please note that the object there will be UIImage type, not URL

Camera photos are not saved by default and don't have local path. So you need to save it by yourself. E.g.:

if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
try? image.pngData()?.write( .... )
}

How to get the URL of a chosen photo in users library or camera?

You are not building your path correctly. There are a few issues:

  1. You are just appending the file name to the pictures path string. You’re missing a slash between the folder and the file name. Obviously, you can add this yourself, but for future reference, if you work with URLs, it would have added the necessary slash for you.

  2. This “pictures” directory is not for iOS. I’d suggest a different folder. Perhaps copy this to a folder in the temporary directory, upload from there, and then clean up when you’re done.

  3. If you’re wondering why your code worked on the simulator, but not the device, it’s because the former doesn’t enforce sandbox rules, whereas the latter will.


As an aside, I’d suggest avoiding “round tripping” through a UIImage unless necessary. Above, we’re dealing with the raw asset, but if you create a UIImage, only to then extract the JPG or PNG representation, you’ll lose information about your asset, and likely make the asset bigger than it needs to be. It’s far more efficient to just grab the image URL, copy that file, and upload:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let imageUrl = info[.imageURL] as? URL else {
return
}

do {
let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("uploads")

try FileManager.default.createDirectory(at: tempDirectory, withIntermediateDirectories: true, attributes: nil)

let fileURL = tempDirectory
.appendingPathComponent(UUID().uuidString)
.appendingPathComponent(imageUrl.pathExtension)

try FileManager.default.copyItem(at: imageUrl, to: fileURL)

// when done, clean up (presumably in the completion handler of the async upload routine)

try FileManager.default.removeItem(at: fileURL)
} catch {
print(error)
}

dismiss(animated: true)
}

How to get URL from UIImage?

CKAsset represents some external file (image, video, binary data and etc). This is why it requires URL as init parameter.

In your case I would recommend to use following steps to upload large image to CloudKit:

  1. Save UIImage to local storage (e.g. documents directory).
  2. Initialize CKAsset with path to image in local storage.
  3. Upload asset to Cloud.
  4. Delete image from local storage when uploading completed.

Here is some code:

// Save image.
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let filePath = "\(path)/MyImageName.jpg"

UIImageJPEGRepresentation(image, 1)!.writeToFile(filePath, atomically: true)

let asset = CKAsset(fileURL: NSURL(fileURLWithPath: filePath)!)
// Upload asset here.

// Delete image.
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {
print(error)
}


Related Topics



Leave a reply



Submit