UIImage from path or filename in Swift 3 - ios

i have a bunch of images in my App's Documents Directory. i want to load one of them in an UIImage that i have in my view. this is what i do:
myImage.image = UIImage(named: "image.jpg") // the file exist but this returns nil
I also tried to init the image using:
myImage.image = UIImage(contentsOfFile: imagePath) //this also doesn't work but the path i got starts (at least in the sim) with file://
Anyone can suggest something? I'm kinda a noob in iOS programming.
Thanks
EDIT:
imagePath comes from:
func getImgPath(name: String) -> String
{
let documentsDirectory = self.getDocumentsDirectory()
let fullpath = documentsDirectory.appendingPathComponent(name)
return fullpath.absoluteString
}

This might help
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("name.png")
let image = UIImage(contentsOfFile: imageURL.path)
// Do whatever you want with the image
}

Try adding your images under Assets.xcassets. Then you'll be able to reference your image by:
UIImage(named: 'yourImageName')
You can conveniently add images with various size settings.

You can get the path of the image as fowllows:
let imagePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("image.jpg")
If this doesn't work, check if your file name is correct.

I understand that if you are downloading images from internet means, you need to convert the URL to UIImage
if let url = URL(string: "your url") {
let data = try? Data(contentsOf: url)
if let imageData = data {
if let image = UIImage(data: imageData) {
imageView.image = image
}
}
}
If i understand your question correct, this will be the answer.

Related

Set UImage form local path URL - causes crash

Setting imageviews in collection view with local path URL like this:
let fileURL = documentsUrl.appendingPathComponent(fileName)
myImageView.image = UIImage(named: fileURL.path)
Causes crash - images are high quality - tried to reduce size also - still crashes the app with no error message.
func getDirectoryPath() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}
let imagePath = (getDirectoryPath() as NSString).appendingPathComponent("/\(file_name).jpg")
let myImageView.image = UIImage(contentsOfFile: imagePath)!
If the image is in the bundle (included with the app), you don't pass the whole path to UIImage(named: ...), only the filename. So your call would be UIImage(named: fileName)
If you have the image in the documents path (you downloaded it from the app) use UIImage(contentsOfFile: fileURL.path)

Grabbing Image Saved from UIImagePickerController?

I'm trying to load an image from the documents path, in my case is showing as file:///var/mobile/Containers/Data/Application/AE7B9E43-E92D-4029-AE8D-4500CB61C15D/Documents/uploadImage.jpg. How would I get that image back so it can be sent out using a POST call? I'm saving the image from the imagePickerController. This is the code I have to save the image...
let fileDirectory : NSURL = {
return try! FileManager.default.url(for: .documentDirectory , in: .userDomainMask , appropriateFor: nil, create: true)
}() as NSURL
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imagePath = fileDirectory.appendingPathComponent("uploadImage.jpg")
guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
// handle failed conversion
presentAlert(title: "Error", message: "Image Failure")
print("jpg error")
return
}
try! imageData.write(to: imagePath!
print("Image Path: \(imagePath!)")
You can get image from document path using
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if let dirPath = documentPath.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("uploadImage.jpg")
let image = UIImage(contentsOfFile: imageURL.path)
// Do whatever you want with the image
}
Save the imagePath somewhere. Then, you can get the image back using:
func imageFromPath(path: String) -> UIImage? {
if let data = NSData(contentsOfFile: path) {
return UIImage(data: data)
}
return nil
}

UIImageJPEGRepresentation | generateJPEGRepresentation saves image as nil? Swift 3

I am currently designing a database management application with Realm, where I have managed to create and retrieve an object successfully. The problem I am having is with updating/editing - specifically updating the UIImage that the user has uploaded. With Realm, I save the path of the image and then retrieve it by loading that path (in Documents Directory).
When the user tries to save the changed image, for some odd reason the UIImageJPEGRepresentation saves the changed image as nil, thus removing the user's image. It's strange because the initial creation of a data object stores it just fine.
I have tried to check whether the image is being passed correctly with some debugging, and have found that it does so just fine and the right path is being saved on.
Here is my update method:
func updateImage() {
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("\(selectedPicPath!)")
if FileManager.default.fileExists(atPath: fileURL.path) {
do {
if profilePic.image != nil {
let image = profilePic.image!.generateJPEGRepresentation()
try! image.write(to: fileURL, options: .atomicWrite)
}
} catch {
print(error)
}
} else {
print("Image Not Added")
}
}
Can anyone see any problems?
let image = profilePic.image!.generateJPEGRepresentation()
Check this line, whether it is returning nil value or data? If nil, then use following code to test your image store, it's working. Also ensure your actual image has JPEG file format extension, that you are trying to generate.
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
// For PNG Image
if let image = UIImage(named: "example.png") {
if let data = UIImagePNGRepresentation() {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
}
For JPG image
if let image = UIImage(named: "example.jpg") {
if let data = UIImageJPEGRepresentation(image, 1.0) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.jpg")
try? data.write(to: filename)
}
}

How I can dowload GIF image in swift

I am developing some tumblr client. And i want to download all photos in dashboard and save them to documentDirectory. Some of them is jpg some are gif. I have successfully download jpg images with this code:
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(fname)
if let pngImageData = UIImagePNGRepresentation(myImage!) {
try pngImageData.write(to: fileURL, options: .atomic)
print(fname + " - saved")
}
} catch {print(fname + " - not saved") }
myImage is the image which is downloaded from URL. This code is work for jpg images but not good for gifs.
And lastly i read these files with this:
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let filePath = documentsURL.appendingPathComponent(fname).path
if FileManager.default.fileExists(atPath: filePath) {
return UIImage(contentsOfFile: filePath)!
}
It's work for jpg but not for gifs. when i try this writing/reading codes on gifs images, i got just image not animation.
Can you show me the way pls with an example will be awesome.
Thank you.
I personally used this tinnie tool for GIFs. Simply add the iOSDevCenters+GIF.swift file directly to your project and use it as shown below
1. Online URL
let imageURL = UIImage.gifImageWithURL(gifURL)
let yourImageView = UIImageView(image: imageURL)
2. Local Filename
let imageName = UIImage.gifImageWithName(imageName)
let yourImageView = UIImageView(image: imageName)
3. Using Data
let imageData = NSData(contentsOf: Bundle.main.url(forResource: "name", withExtension: ".gif"))
let imageData = UIImage.gifImageWithData(imageData)
let yourImageView = UIImageView(image: imageData)
Actually your first code is not working correctly either.
What you are receiving is the image. You do not need or want to translate it into some other kind of image (UIImagePNGRepresentation). Just save the data. Later, read the data directly into a UIImage.
I think there is no problem with downloading and you are just trying to present it as a png; instead try to present this saved data with this library, for example
Try this:
#import AssetsLibrary
let lib = ALAssetsLibrary()
let data = NSData(contentsOfURL: getCurrentGIFURL)
lib.writeImageDataToSavedPhotosAlbum(data, metadata: nil) { (url, err) in
}

Load image form Gallery in swift from path given by UIImagePickerViewController?

I am saving path in Database return by UIImagepicker from Gallery
let imageURL = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageURL.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String
//let localPath = documentDirectory.stringByAppendingPathComponent(imageName!)
let imagePath = String("\(documentDirectory)/\(imageName!)")
where path look like
/Users/kshitijghule/Library/Developer/CoreSimulator/Devices/3AC7B500-E980-4A00-BC32-34FA3C7DDE8A/data/Containers/Data/Application/838FB5A1-4448-46C9-8BEC-2E939668B97D/Documents/asset.JPG
Now i want load this image from this path.
i used this code
let url = NSURL(string:"/Users/kshitijghule/Library/Developer/CoreSimulator/Devices/3AC7B500-E980-4A00-BC32-34FA3C7DDE8A/data/Containers/Data/Application/838FB5A1-4448-46C9-8BEC-2E939668B97D/Documents/asset.JPG")!//path from database but mention static
let imageData = NSData(contentsOfURL:url)!
cell?.petImageView.image = UIImage(data: imageData)
But i am getting crash at line
let imageData = NSData(contentsOfURL:url)!
How to fix this issue? It will work on device ?
If you are storing images in the document directory store only image name in the db
At the time of retrieval append the current document directory path with your image name like you done at save time
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String
//let localPath = documentDirectory.stringByAppendingPathComponent(imageName!)
//imageName which you have stored in the db at retrieval time
let imagePath = String("\(documentDirectory)/\(imageName!)")
let url = NSURL(string:imagePath)
let imageData = NSData(contentsOfURL:url)!
as i have also this type of issue at last if found that the app number of simulator(838FB5A1-4448-46C9-8BEC-2E939668B97D) is changes which cause the issue
Hope this may solve your issue
I have answered a similar question here.You only have to save those paths to your database, and from the database path you can retrieve those images.
Save image in Document Directory taken from Gallery or Camera.
func origionalImage(origionalImage: UIImage!, editedImage: UIImage!, userInfo info: [NSObject : AnyObject]!) {
let imageData = NSData(data:UIImagePNGRepresentation(origionalImage)!)
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let docs: String = paths[0]
let imageName = self.randomStringWithLength(6) as String
//imageName can save in sqlite to load image later
let fullPath = String("\(docs)/\(imageName).png")
print(fullPath)
let result = imageData.writeToFile(fullPath, atomically: true)
print("FILE WRITTEN SUCCESS=>:\(result)")
}
Load Image from Database
let tempDBObject = self.petListArray[indexPath.row] as! Database
cell?.petName.text = tempDBObject.Hname
//Doc Path
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String
let imagePath = String("\(documentDirectory)/\(tempDBObject.Hpath!)")
if imagePath == "" {
}else{
cell?.petImageView.image = UIImage(contentsOfFile: imagePath)
}

Resources