2009-12-20 24 views

Trả lời

11

Những phương pháp này cho phép bạn lưu vào và lấy một hình ảnh từ thư mục tài liệu trên iphone

+ (void)saveImage:(UIImage *)image withName:(NSString *)name { 
    NSData *data = UIImageJPEGRepresentation(image, 1.0); 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name]; 
    [fileManager createFileAtPath:fullPath contents:data attributes:nil]; 
} 

+ (UIImage *)loadImage:(NSString *)name { 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];  
    UIImage *img = [UIImage imageWithContentsOfFile:fullPath]; 

    return img; 
} 
+0

Cảm ơn bạn đã thời gian phản ứng nhanh chóng. Và câu trả lời chính xác. – Jaba

+4

Và tài liệu này đến từ đâu? – jjxtra

+2

Chi tiết về thư mục tài liệu tại đây http://stackoverflow.com/questions/6907381/what-is-the-documents-directory-nsdocumentdirectory/6907432#6907432 –

2

Bên cạnh đó, bạn không bao giờ muốn lưu bất cứ điều gì vào tmp thư mục thực tế mà bạn muốn xung quanh sau khi ứng dụng tắt. Thư mục tmp có thể bị hệ thống thanh lọc. Theo định nghĩa, nó chỉ tồn tại để giữ các tệp nhỏ chỉ cần thiết khi ứng dụng đang chạy.

Các tệp bạn muốn giữ lại phải luôn đi vào thư mục documents.

+0

Cảm ơn bạn Tôi không biết điều này – Jaba

1

Các chưa được kiểm tra Swift tinh chỉnh cho câu trả lời chọn:

class func saveImage(image: UIImage, withName name: String) { 
    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String 
    var data: NSData = UIImageJPEGRepresentation(image, 1.0)! 
    var fileManager: NSFileManager = NSFileManager.defaultManager() 

    let fullPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(name) 
    fileManager.createFileAtPath(fullPath.absoluteString, contents: data, attributes: nil) 
} 

class func loadImage(name: String) -> UIImage { 
    var fullPath: String = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(name).absoluteString 
    var img:UIImage = UIImage(contentsOfFile: fullPath)! 
    return img 
} 
2

Tested Mã cho nhanh chóng

//to get document directory path 
    func getDocumentDirectoryPath() -> NSString { 
     let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
     let documentsDirectory = paths[0] 
     return documentsDirectory 
    } 

Gọi sử dụng

if let data = UIImagePNGRepresentation(img) { 
    let filename = self.getDocumentDirectoryPath().stringByAppendingPathComponent("resizeImage.png") 
    data.writeToFile(filename, atomically: true) 
} 
2

Swift 3 Xcode 8,2

Tài liệu thư mục có được:

func getDocumentDirectoryPath() -> NSString { 
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) 
    let documentsDirectory = paths[0] 
    return documentsDirectory as NSString 
} 

Tiết kiệm:

func saveImageToDocumentsDirectory(image: UIImage, withName: String) -> String? { 
    if let data = UIImagePNGRepresentation(image) { 
     let dirPath = getDocumentDirectoryPath() 
     let imageFileUrl = URL(fileURLWithPath: dirPath.appendingPathComponent(withName) as String) 
     do { 
      try data.write(to: imageFileUrl) 
      print("Successfully saved image at path: \(imageFileUrl)") 
      return imageFileUrl.absoluteString 
     } catch { 
      print("Error saving image: \(error)") 
     } 
    } 
    return nil 
} 

Chở Hàng:

func loadImageFromDocumentsDirectory(imageName: String) -> UIImage? { 
    let tempDirPath = getDocumentDirectoryPath() 
    let imageFilePath = tempDirPath.appendingPathComponent(imageName) 
    return UIImage(contentsOfFile:imageFilePath) 
} 

Ví dụ:

//TODO: pass your image to the actual method call here: 
let pathToSavedImage = saveImageToDocumentsDirectory(image: imageToSave, withName: "imageName.png") 
if (pathToSavedImage == nil) { 
    print("Failed to save image") 
} 

let image = loadImageFromDocumentsDirectory(imageName: "imageName.png") 
if image == nil { 
    print ("Failed to load image") 
} 
0

Swift 4 thực hiện:

// saves an image, if save is successful, returns its URL on local storage, otherwise returns nil 
func saveImage(_ image: UIImage, name: String) -> URL? { 
    guard let imageData = UIImageJPEGRepresentation(image, 1) else { 
     return nil 
    } 
    do { 
     let imageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name) 
     try imageData.write(to: imageURL) 
     return imageURL 
    } catch { 
     return nil 
    } 
} 

// returns an image if there is one with the given name, otherwise returns nil 
func loadImage(withName name: String) -> UIImage? { 
    let imageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name) 
    return UIImage(contentsOfFile: imageURL.path) 
} 

dụ sử dụng (giả sử chúng ta có một hình ảnh):

let image = UIImage(named: "milan") 

let url = saveImage(image, name: "savedMilan.jpg") 
print(">>> URL of saved image: \(url)") 

let reloadedImage = loadImage(withName: "savedMilan.jpg") 
print(">>> Reloaded image: \(reloadedImage)") 
Các vấn đề liên quan