How to Use Writetofile to Save Image in Document Directory

how to use writeToFile to save image in document directory?

The problem there is that you are checking if the folder not exists but you should check if the file exists. Another issue in your code is that you need to use url.path instead of url.absoluteString. You are also saving a jpeg image using a "png" file extension. You should use "jpg".

edit/update:

Swift 4.2 or later

do {
// get the documents directory url
let documentsDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
print("documentsDirectory:", documentsDirectory.path)
// choose a name for your image
let fileName = "image.jpg"
// create the destination file url to save your image
let fileURL = documentsDirectory.appendingPathComponent(fileName)
// get your UIImage jpeg data representation and check if the destination file url already exists
if let data = image.jpegData(compressionQuality: 1),
!FileManager.default.fileExists(atPath: fileURL.path) {
// writes the image data to disk
try data.write(to: fileURL)
print("file saved")
}
} catch {
print("error:", error)
}

To write the image at the destination regardless if the image already exists or not you can use .atomic options, if you would like to avoid overwriting an existing image you can use withoutOverwriting instead:

try data.write(to: fileURL, options: [.atomic])

Saving image to .documentsDirectory, and as a String to store path in local Realm

jpegData is a instance method of UIImage. Let use:

selectedImageView.image?.jpegData()

UIImage save to document directory with Low memory usage

Trying to improve Lefteris' solution is too check if there is space available in the first place.

That way, you can ask the user what he wants to do "Cancel" or "Save (anyway)", and he knows he's saving a 3mb picture in a 2mb storage it's probably gonna fail.

Then he can free space if necessary ; always give the user choice & information, he knows better than you what's happening anyway.

According to this answer : https://stackoverflow.com/a/8036586/3603502

you can get the available disk space. Translate it in megabytes if necessary, compare with picture size, and if the difference is less than, say, 100x, show error message saying "are you sure". Then he can do it or not, and if it fails you can show error like Lefteris suggested. And I'll insist on what he said because he was right :

You should always manipulate files with error statements so you can come back with information if it fails for any reason. (and display to user if necessary).

How to save a UIImage to documents directory?

One Suggestion: Save images to Library/Caches if that can be downloaded again as per apple's guide line.


As simple as this:

func saveImageToDocumentDirectory(_ chosenImage: UIImage) -> String {
let directoryPath = NSHomeDirectory().appending("/Documents/")
if !FileManager.default.fileExists(atPath: directoryPath) {
do {
try FileManager.default.createDirectory(at: NSURL.fileURL(withPath: directoryPath), withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
}
let filename = NSDate().string(withDateFormatter: yyyytoss).appending(".jpg")
let filepath = directoryPath.appending(filename)
let url = NSURL.fileURL(withPath: filepath)
do {
try UIImageJPEGRepresentation(chosenImage, 1.0)?.write(to: url, options: .atomic)
return String.init("/Documents/\(filename)")

} catch {
print(error)
print("file cant not be save at path \(filepath), with error : \(error)");
return filepath
}
}

Swift4:

func saveImageToDocumentDirectory(_ chosenImage: UIImage) -> String {
let directoryPath = NSHomeDirectory().appending("/Documents/")
if !FileManager.default.fileExists(atPath: directoryPath) {
do {
try FileManager.default.createDirectory(at: NSURL.fileURL(withPath: directoryPath), withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
}

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddhhmmss"

let filename = dateFormatter.string(from: Date()).appending(".jpg")
let filepath = directoryPath.appending(filename)
let url = NSURL.fileURL(withPath: filepath)
do {
try chosenImage.jpegData(compressionQuality: 1.0)?.write(to: url, options: .atomic)
return String.init("/Documents/\(filename)")

} catch {
print(error)
print("file cant not be save at path \(filepath), with error : \(error)");
return filepath
}
}

Get image from documents directory swift

You are finding the document directory path at runtime for writing the image, for reading it back, you can use the exact logic:

Swift 3 and Swift 4.2

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

Swift 2

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
{
if paths.count > 0
{
if let dirPath = paths[0] as? String
{
let readPath = dirPath.stringByAppendingPathComponent("Image2.png")
let image = UIImage(contentsOfFile: readPath)
// Do whatever you want with the image
}
}
}

How to save image or video from UIPickerViewController to document directory?

  • Use following steps to save Image to documents directory

Step 1: Get a path to document directory

let path = try! NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)

Step 2: Append FileName in path

let newPath = path.stringByAppendingPathComponent("image.jpg")

Step 3: Decide filetype of Image either JPEG or PNG and convert image to data(byte)

//let pngImageData = UIImagePNGRepresentation(image) // if you want to save as PNG
let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG

Step 4: write file to created path

let result = jpgImageData!.writeToFile(newPath, atomically: true)

Add above code into your didFinishPickingImage function.

  • Use following func to save video to documents directory

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) 
    {
    // *** store the video URL returned by UIImagePickerController *** //
    let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL

    // *** load video data from URL *** //
    let videoData = NSData(contentsOfURL: videoURL)

    // *** Get documents directory path *** //
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]

    // *** Append video file name *** //
    let dataPath = documentsDirectory.stringByAppendingPathComponent("/videoFileName.mp4")

    // *** Write video file data to path *** //
    videoData?.writeToFile(dataPath, atomically: false)
    }


Related Topics



Leave a reply



Submit