从IOS上的UIView将图像保存到应用程序文档文件夹


114

我有一个UIImageView,它允许用户放置并保存图像,直到可以保存为止。问题是,我不知道如何实际保存和检索放置在视图中的图像。

我已经将图像检索并放置在UIImageView中,如下所示:

//Get Image 
- (void) getPicture:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = (sender == myPic) ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentModalViewController:picker animated:YES];
    [picker release];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    myPic.image = image;
    [picker dismissModalViewControllerAnimated:YES];
}

它在我的UIImageView中显示选定的图像就很好了,但是我不知道如何保存它。我将视图的所有其他部分(主要是UITextfield)保存在Core Data中。我已经搜索了很多,然后尝试了很多人建议的代码,但是要么我没有正确输入代码,要么这些建议与我的代码设置方式不符。可能是前者。我想使用与将文本保存在UITextFields中相同的操作(保存按钮)将图像保存在UIImageView中。这是我保存UITextField信息的方式:

// Handle Save Button
- (void)save {

    // Get Info From UI
    [self.referringObject setValue:self.myInfo.text forKey:@"myInfo"];

就像我之前说过的那样,我尝试了几种方法来使它起作用,但无法掌握它。我一生中第一次想对无生命的物体造成身体伤害,但我设法克制了自己。

我希望能够将用户放置的图像保存到应用程序的documents文件夹中的UIImageView中,然后可以将其检索并将其放置在另一个UIImageView中,以便在用户将该视图推入堆栈时显示。任何帮助是极大的赞赏!

Answers:


341

很好,伙计。不要伤害自己或他人。

您可能不想将这些图像存储在Core Data中,因为如果数据集太大,这会影响性能。最好将图像写入文件。

NSData *pngData = UIImagePNGRepresentation(image);

这会提取您捕获的图像的PNG数据。从这里,您可以将其写入文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory 
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file

以后阅读它的方式相同。像上面一样构建路径,然后:

NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];

您可能想要做的是创建一个为您创建路径字符串的方法,因为您不希望该代码随处可见。它可能看起来像这样:

- (NSString *)documentsPathForFileName:(NSString *)name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  
    NSString *documentsPath = [paths objectAtIndex:0];

    return [documentsPath stringByAppendingPathComponent:name]; 
}

希望对您有所帮助。


2
完全正确-只是要提及Apple存储指南,因此取决于图像的性质,应将其存储在缓存中
Daij-Djan

我遵循了您的建议和代码。但它不会出现在“照片”部分中。这怎么发生的?
NovusMobile

@DaniloCampos如何在Documents Directory中创建一个文件夹,然后在该文件夹中保存文件?
Pradeep Reddy Kypa

3

Swift 3.0版本

let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
        
let img = UIImage(named: "1.jpg")!// Or use whatever way to get the UIImage object
let imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("1.jpg"))// Change extension if you want to save as PNG

do{
    try UIImageJPEGRepresentation(img, 1.0)?.write(to: imgPath, options: .atomic)//Use UIImagePNGRepresentation if you want to save as PNG
}catch let error{
    print(error.localizedDescription)
}

2

这是Fangming Ning 对Swift 4.2 的回答,它使用一种推荐的Swifty方法进行了更新,该方法用于检索文档目录路径并提供了更好的文档。这种新方法也归功于方明宁。

guard let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
    return
}

//Using force unwrapping here because we're sure "1.jpg" exists. Remember, this is just an example.
let img = UIImage(named: "1.jpg")!

// Change extension if you want to save as PNG.
let imgPath = documentDirectoryPath.appendingPathComponent("1.jpg")

do {
    //Use .pngData() if you want to save as PNG.
    //.atomic is just an example here, check out other writing options as well. (see the link under this example)
    //(atomic writes data to a temporary file first and sending that file to its final destination)
    try img.jpegData(compressionQuality: 1)?.write(to: imgPath, options: .atomic)
} catch {
    print(error.localizedDescription)
}

在此处检查所有可能的数据写入选项。


这样对吗?在回答另一个问题时我发现与fileURLWithPath在一起absoluteString是错误的。
dumbledad

@dumbledad感谢您提供的信息,我已经更新了答案,并重新编写了Swift 4.2的代码。
塔玛斯·森格尔

2
#pragma mark - Save Image To Local Directory

- (void)saveImageToDocumentDirectoryWithImage:(UIImage *)capturedImage {
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/images"];
    
    //Create a folder inside Document Directory
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

    NSString *imageName = [NSString stringWithFormat:@"%@/img_%@.png", dataPath, [self getRandomNumber]] ;
    // save the file
    if ([[NSFileManager defaultManager] fileExistsAtPath:imageName]) {
        // delete if exist
        [[NSFileManager defaultManager] removeItemAtPath:imageName error:nil];
    }
    
    NSData *imageDate = [NSData dataWithData:UIImagePNGRepresentation(capturedImage)];
    [imageDate writeToFile: imageName atomically: YES];
}


#pragma mark - Generate Random Number

- (NSString *)getRandomNumber {
    NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); // returned as a double
    long digits = (long)time; // this is the first 10 digits
    int decimalDigits = (int)(fmod(time, 1) * 1000); // this will get the 3 missing digits
    //long timestamp = (digits * 1000) + decimalDigits;
    NSString *timestampString = [NSString stringWithFormat:@"%ld%d",digits ,decimalDigits];
    return timestampString;
}

1

带有扩展功能的Swift 4

extension UIImage{

func saveImage(inDir:FileManager.SearchPathDirectory,name:String){
    guard let documentDirectoryPath = FileManager.default.urls(for: inDir, in: .userDomainMask).first else {
        return
    }
    let img = UIImage(named: "\(name).jpg")!

    // Change extension if you want to save as PNG.
    let imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("\(name).jpg").absoluteString)
    do {
        try UIImageJPEGRepresentation(img, 0.5)?.write(to: imgPath, options: .atomic)
    } catch {
        print(error.localizedDescription)
    }
  }
}

使用范例

 image.saveImage(inDir: .documentDirectory, name: "pic")

0

在Swift中:

let paths: [NSString?] = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .LocalDomainMask, true)
if let path = paths[0]?.stringByAppendingPathComponent(imageName) {
    do {
        try UIImagePNGRepresentation(image)?.writeToFile(path, options: .DataWritingAtomic)
    } catch {
        return
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.