Saving Image to Documents Directory and Retrieving for Email Attachment

Saving image to Documents directory and retrieving for email attachment


- (IBAction)getImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
}

This should get you started!

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])

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
}
}

Save and get image from folder inside Documents folder on iOS wrong path

You can initialize your path variables as global variables at the top of your class, then just modify them within your requestImage method.

Then when you want to retrieve those images, you can just use the same variable name to ensure that it is the exact same path.

EDIT*
I think you may need to be reading some NSData instead. You can use UIImagePNGRepresentation or UIImageJPEGRepresentation to write your file to the documents directory. I found a tutorial here

Save image captured by Camera into Documents Directory in ios

Try

UIImage *image = [UIImage imageNamed:@"Image.jpg"];
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"New Folder"];
// New Folder is your folder name
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];

NSString *fileName = [stringPath stringByAppendingFormat:@"/image.jpg"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
[data writeToFile:fileName atomically:YES];


Related Topics



Leave a reply



Submit