Save image to the File Directory

I am trying to save images using the File Directory but I am unable to without an error saying

No Such Folder.

Here's my code, I am not sure where I am going wrong

// Write image to directory
func writeImageToPath(_ path: String, image: UIImage) {
    print("Write image to directory")

    // get the documents directory url
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

    let folderURL = documentsURL.appendingPathComponent("upload")

    if !FileManager.default.fileExists(atPath: folderURL.path) {
        do {
            try FileManager.default.createDirectory(atPath: folderURL.path, withIntermediateDirectories: true, attributes: nil)
        }
        catch {}
    }

    let fileURL = folderURL.appendingPathComponent(path)
    let data = UIImageJPEGRepresentation(image, 0.9)
    do {
        try data!.write(to: fileURL)
    }
    catch {}

}

// load image from directory
func loadImageFromPath(_ path: String) -> UIImage? {

    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

    let folderURL = documentsURL.appendingPathComponent("upload")

    let fileURL = folderURL.appendingPathComponent(path)

    if FileManager.default.fileExists(atPath: fileURL.path) {
        //Get Image And upload in server
        print("fileURL.path \(fileURL.path)")

        do{
            let data = try Data.init(contentsOf: fileURL)
            let image = UIImage(data: data)
            return image
        }catch{
            print("error getting image")
        }
    } else {
        print("No image in directory")
    }

    return nil
}

How can I correctly save and load images from the directory ?

Roe,

I have been following below snippet of code in most of the projects:

To save image in folder, use below function:

func addImageInFolder(image : UIImage,filename:String){
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let folderURL = documentsURL.appendingPathComponent("upload")
    if !FileManager.default.fileExists(atPath: folderURL.path) {
        do {
            try FileManager.default.createDirectory(atPath: folderURL.path, withIntermediateDirectories: true, attributes: nil)
        }
        catch {}
    }
    let fileURL = folderURL.appendingPathComponent(filename)
    let data = UIImageJPEGRepresentation(image, 0.9)
    do {
        try data!.write(to: fileURL)
    }
    catch {}
}

Use below function to remove image from stored folder:

let fileURL = documentsURL.appendingPathComponent("upload/\(filename ?? "")")

            if FileManager.default.fileExists(atPath: fileURL.absoluteString){
                do{
                    try FileManager.default.removeItem(at: fileURL)
                }catch{
                    print("\(sigStr ?? "") delete file delete error")
                }

            }

To Get image from folder:

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                //TODO: -Get dateTime For get image URL-
                let fileURL = documentsURL.appendingPathComponent("upload/\(fileName)")
                if FileManager.default.fileExists(atPath: fileURL.path) {
                    //Get Image And upload in server
                    print("fileURL.path \(fileURL.path)")

                    do{
                        let data = try Data.init(contentsOf: fileURL)
                        imageView.image = UIImage(data: data)
                    }catch{

                    }
                }

Right-click the .exe file and select the “Run as administrator” option. After the app loads, open the “Setup” menu, and then choose the “Add to Directory Context Menu” option. Now, to generate a quick listing, just right-click a folder and choose the “Open in Directory List + Print” command from the context menu.

Swift 4.2

func saveAndGetImageFromDirectory(_ data: Data, name: String, completionHandler: @escaping (URL?)->()) {
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        var imageURL:URL!

        imageURL = documentsURL.appendingPathComponent(name)

        do {
            try data.write(to: imageURL)

            var documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            documentsPath = documentsPath + "/\(name)"
            completionHandler(URL.init(fileURLWithPath: documentsPath))
        } catch let error {
            print(error)
        }
    }

To find the directory of the image catalog, WRKIMGCLGE imagecatalogxx. If saving to save file, pre-create two save files on both the target and source systems using the CRTSAVF command as listed in the example steps below.

Swift 4:
try this code maybe it will helps you.
//saving image in directory and
            let fileManager = FileManager.default
            //get the image path
            let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(imageName)
            //get the image we took from gallery
            let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
            //get the PNG data for this image
            let data = image!.pngData()
            //store it in the document directory
            fileManager.createFile(atPath: imagePath as String, contents: data, attributes: nil)

Bitmap bmpLarge = new Bitmap(ofdFlagsLarge.FileName); bmpLarge.Save(@"\..\..\" + strLargePath); /* ERROR */ Can someone please assist me to save a image from the local PC directory itself to other directory on the same machine..

Where does the image come from? This article illustrates at some frequently-used methods for image handling in .NET : Image in C#: Save, Resize, and Convert to Binary it will give you much more information about how to handle images. Hope it helps. Best wishes, This response contains a reference to a third party World Wide Web site.

1 – Press the Windows key and the Print Screen key at the same time. Note: The Print Screen key is usually labeled either PrtScn, PrntScrn or Print Scr, depending on the keyboard. 2 – Press the Windows + E key combination to open “File Explorer”, then navigate to the Pictures > Screenshots folder.

The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. Image.save() Saves this image under the given filename. If no format is specified, the format to use is determined from the

Comments
  • Instead of providing the answer I would like to tell you the mistake you're making. First you will have to create the directory before writing the imageData. Second you need to use extensions .jpg, .png for image name in full path.
  • Hey, thanks for your answer. I no longer get any errors when saving the image, however when loading I do not get any results. I have updated my question with my load function, how can I load the image and return it ? Thank you for your help
  • @A.Roe I have updated my answer. Hope it will solve your problem.
  • Thank you, but for some reason when retrieving the image the file isn't found, I have updated my code in my question and you can see where the console prints print("No image in directory"), any ideas ?
  • NSSearchPathForDirectoriesInDomains is outdated and objective-c-ish. And never build paths with + and concatenating strings
  • Don't use (NS)String to build paths. NSSearchPathForDirectoriesInDomains is outdated. Use the URL related API of FileManager and methods like appendingPathComponent() have been moved to URL.