Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert code objective c to Swift to save image?

I have seen this code in other post, for save pictures:

  // Create path.
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,      NSUserDomainMask, YES);
 NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

An d I'm trying convert to swift for save a picture take with avfoundatioin but I dont know type NSDocumentDirectory and NSUserDomainMask here How can convert this??

Thanks!!

like image 679
user3745888 Avatar asked Jun 19 '14 07:06

user3745888


People also ask

How do I save an image in a directory in Swift?

To write the image data to the Documents directory, we invoke the write(to:) method on the Data object. Because the write(to:) method is throwing, we wrap the method call in a do-catch statement and prefix it with the try keyword.

How do I save an image in Userdefaults Swift 5?

We ask the FileManager class for the URL of the Documents directory and append the name of the file, landscape. png, to the URL. Writing a Data object to disk is a throwing operation so we wrap it in a do-catch statement. If the operation is successful, we store the URL in the user's defaults database.


3 Answers

As follows:

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("Image.png")
            let image = UIImage(named: readPath)
            let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
            UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
        }
    }
}

"paths" is an AnyObject[], so you have to check that its elements can be converted to String.

Naturally, you wouldn't actually use "NSDocumentDirectory" as the name, I just did it for clarity.

Update for Xcode 7.2

NSSearchPathForDirectoriesInDomains now returns [String] rather than [AnyObject]? so use

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
    // ...
}

The fact that .stringByAppendingPathComponent is also deprecated is dealt with in this answer...

like image 104
Grimxn Avatar answered Oct 06 '22 00:10

Grimxn


Here is what I use:

    let fileManager = NSFileManager.defaultManager()
    let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
    let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
    let documentsURL = fileManager.URLsForDirectory(nsDocumentDirectory, inDomains: nsUserDomainMask).last
like image 40
William Entriken Avatar answered Oct 05 '22 23:10

William Entriken


This is just a rework of @पवन answer working for Swift 3

import Foundation
import UIKit
import ImageIO
import MobileCoreServices

extension UIImage
{
    func write(at path:String) -> Bool
    {
        let result = CGImageWriteToFile(image: self.cgImage!, filePath: path)
        return result
    }

    private func CGImageWriteToFile(image:CGImage, filePath:String) -> Bool
    {
        let imageURL:CFURL = NSURL(fileURLWithPath: filePath)
        var destination:CGImageDestination? = nil

        let ext = (filePath as NSString).pathExtension.lowercased()
        if ext == "jpg" || ext == "jpeg"
        {
            destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeJPEG, 1, nil)
        }
        else if ext == "png" || ext == "pngf"
        {
            destination = CGImageDestinationCreateWithURL(imageURL, kUTTypePNG, 1, nil)
        }
        else if ext == "tiff" || ext == "tif"
        {
            destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeTIFF, 1, nil)
        }
        else  if ext == "bmpf" || ext == "bmp"
        {
            destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeBMP, 1, nil)
        }


        guard destination != nil else {
            fatalError("Did not find any matching path extension to store the image")
        }

        CGImageDestinationAddImage(destination!, image, nil)

        if CGImageDestinationFinalize(destination!)
        {
            return true
        }
        return false
    }
}

And the usage

let pickedImage = UIImage()
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString).appendingPathComponent("image.tif")
if pickedImage.write(at: path) == false
{
    print("failed to write file to disk!")
}
like image 31
zero3nna Avatar answered Oct 06 '22 00:10

zero3nna