113

imagePicker からのファイルがある場合UIImage、ドキュメント ディレクトリのサブフォルダーに保存するにはどうすればよいですか?

4

9 に答える 9

133

もちろん、アプリのドキュメントフォルダーにサブフォルダーを作成できます。あなたはそれをするために使用NSFileManagerします。

UIImagePNGRepresentation画像をNSDataに変換し、それをディスクに保存するために使用します。

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

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

ちなみに、CoreDataはイメージをディスクに保存することとは何の関係もありません。

于 2012-07-21T12:52:47.683 に答える
26

スウィフト 3 では:

// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/MyImageName.png"

// Save image.
UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)
于 2015-12-29T01:30:10.450 に答える
25

画像の表現を特定の形式(たとえば、JPEGまたはPNG)として作成してから、表現を呼び出す必要がwriteToFile:atomically:あります。

UIImage *image = ...;
NSString  *path = ...;
[UIImageJPEGRepresentation(image, 1.0) writeToFile:path atomically:YES];
于 2012-07-21T12:50:31.693 に答える
6
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];

ここで、pathは書き込み先のファイルの名前です。

于 2012-07-21T12:54:55.053 に答える
4

まず、Documentsディレクトリを取得する必要があります

/* create path to cache directory inside the application's Documents directory */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"fileName"];

次に、写真をファイルに保存する必要があります

NSData *photoData = UIImageJPEGRepresentation(photoImage, 1);
[photoData writeToFile:filePath atomically:YES];
于 2012-07-21T12:54:37.143 に答える