Swift 3 and Xcode 8 : Get Image From URL Path Stored in SQLITE Database Field - swift

I have Implemented the Following code to add the image into Document directory and store the Path in my sqlite Database
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePath = imagesDirectoryPath + "/\(Date().description.replacingOccurrences(of: " ", with: "")).png"
print(imagePath)
let data = UIImagePNGRepresentation(image)
print(data!)
let success = FileManager.default.createFile(atPath: imagePath, contents: data, attributes: nil)
print(success)
dismiss(animated: true) { () -> Void in
}
}
Can Anyone help me how to get image back into My Tableview Using this Path as shown in the Image.

In the Table View cellForRowAt Method Or In Ur case if u want to display image in some other Case
You can Simply Do this by
let imageURL = URL(fileURLWithPath: student.Image_URL)
cell.imgProfileDisplay.image = UIImage(contentsOfFile: imageURL.path)
This will convert the image from the URL that we store in our DataBAse.
For Full Source Code of the Implementation kindly Comment.
Thanks

Related

How to grab all metadata from any image?

I have been searching google and could not find a solution for my problem. I have some code that grabs metadata from images the user picks from the image picker. The problem is that my code doesn't grab ALL metadata from HEIC and RAW images. I set up some print statements to find out which data my code doesn't grab from HEIC.
Manufacturer not found
Camera model not found
Camera software not found
Aperture not found
Focal length not found
ISO not found
Shutter speed not found
//And this is my metadata extracting code block
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[.originalImage] as? UIImage
let url = info[.imageURL]
let optionalImageData = try? Data(contentsOf: url as! URL)
guard let imageData = optionalImageData else { return }
let source: CGImageSource = CGImageSourceCreateWithData(imageData as CFData, nil)!
let metadata = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [AnyHashable: Any]
print(metadata!)
self.dismiss(animated: true, completion: nil)
}
I'm going to guess that you have not obtained user permission to access the photos library. You are allowed to present the picker even so, but the information that you can receive in response is very limited. If you have user permission, you can receive the image as a PHAsset and you can get the desired metadata from the photos library.

How To Add A Image In CoreData And How to Save The Image In CoreData [duplicate]

This question already has answers here:
Saving Picked Image to CoreData
(2 answers)
Closed 4 years ago.
How to add an image in core data? The image type what that I have selected. And how to save the core data image. How can I add a image?
Step 1:- Save the image in Document Directory
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
let newPath = path.appendingPathComponent("image.jpg") //Possibly you Can pass the dynamic name here
// Save this name in core Data using you code as a String.
let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
do {
try jpgImageData!.write(to: newPath)
} catch {
print(error)
}
}}
Step:-2: Fetch the Image back from the Document Directory and display index path row wise in table view cell.
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image.png") //Pass the image name fetched from core data here
let image = UIImage(contentsOfFile: imageURL.path)
cell.imageView.image = image
}
This is simple and More convenient Method

How to create a URL for an Image using Swift

I have used following line of code for picking an image from the Photo Library. Now I want to create a URL
for those images, if it's possible.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.imageView.image = image
picker.dismiss(animated: true) {
// Completion block
}
}
How to create a URL for an UIImage?
Try using let url = info[UIImagePickerControllerMediaURL] as! URL

Save image in Realm

I'm trying to pick image from device's Photo Library in method:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
userPhoto.image = info[UIImagePickerControllerOriginalImage] as! UIImage?
userPhoto.contentMode = .scaleAspectFill
userPhoto.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
and save this picture in Realm (as NSData):
asset.assetImage = UIImagePNGRepresentation(userPhoto.image!)! as NSData?
...
try! myRealm.write
{
user.assetsList.append(asset)
myRealm.add(user)
}
After build succeeded and trying to pick and save image (in the app) i have app error:
'Binary too big'
What i'm doing wrong?
P.S. Sorry for my English :)
After some actions i have this code. But it's overwrite my image.
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
}
userPhoto.image = image
userPhoto.contentMode = .scaleAspectFill
userPhoto.clipsToBounds = true
urlCatch = (localPath?.path)!
self.dismiss(animated: true, completion: nil);
}
Don't save the image itself into realm, just save the location of the image into realm as String or NSString and load the image from that saved path. Performance wise it's always better to load images from that physical location and your database doesn't get too big
func loadImageFromPath(_ path: NSString) -> UIImage? {
let image = UIImage(contentsOfFile: path as String)
if image == nil {
return UIImage()
} else{
return image
}
}
or you just save the image name, if it's in your documents directory anyhow
func loadImageFromName(_ imgName: String) -> UIImage? {
guard imgName.characters.count > 0 else {
print("ERROR: No image name")
return UIImage()
}
let imgPath = Utils.getDocumentsDirectory().appendingPathComponent(imgName)
let image = ImageUtils.loadImageFromPath(imgPath as NSString)
return image
}
and here a rough example how to save a captured image to your directory with a unique name:
#IBAction func capture(_ sender: AnyObject) {
let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (imageDataSampleBuffer, error) -> Void in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
//self.stillImage = UIImage(data: imageData!)
//self.savedImage.image = self.stillImage
let timestampFilename = String(Int(Date().timeIntervalSince1970)) + "someName.png"
let filenamePath = URL(fileReferenceLiteralResourceName: getDocumentsDirectory().appendingPathComponent(timestampFilename))
let imgData = try! imageData?.write(to: filenamePath, options: [])
})
/* helper get Document Directory */
class func getDocumentsDirectory() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
//print("Path: \(documentsDirectory)")
return documentsDirectory as NSString
}
https://realm.io/docs/objc/latest/#current-limitations
maximum data size is 16 MB . this is limitation of realm
Depending on how your serializing the image data (for example if it's a lossless bitmap), it's quite possible that this data exceed 16MB, which as you've stated is Realm's maximum supported size for binary properties.
When you invoke NSData.length, how large does it say your data is?

Firebase retrieve image from URL save with Firebase database

I have saved an image to the Firebase storage and also saved the imageURL to Firebase database, but how can I get the image back by the URL saved in firebase database? Here is how I save it
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
userPhoto.image = image
dismissViewControllerAnimated(true, completion: nil)
var data = NSData()
data = UIImageJPEGRepresentation(userPhoto.image!, 0.8)!
// set upload path
let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("userPhoto")"
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
self.storageRef.child(filePath).putData(data, metadata: metaData){(metaData,error) in
if let error = error {
print(error.localizedDescription)
return
} else {
// store downloadURL
let downloadURL = metaData!.downloadURL()!.absoluteString
// store downloadURL at database
self.databaseRef.child("users").child(FIRAuth.auth()!.currentUser!.uid).updateChildValues(["userPhoto": downloadURL])
}
}
}
Here's one way of doing it, by downloading the data and then creating a UIImage for it:
self.storage.referenceForURL(url).dataWithMaxSize(25 * 1024 * 1024, completion: { (data, error) -> Void in
let image = UIImage(data: data!)
chatMessage.image = image!
self.messages.append(chatMessage)
self.tableView.reloadData()
self.scrollToBottom()
})
This code comes from the Zero To App talk at Google I/O. Complete code is available in this gist