如何动态保存图像

时间:2012-07-11 11:02:11

标签: objective-c

我在我的应用中使用照片库。从照片库或相机中选择图像后,我想将该图像保存到我的Documents文件夹中。所以在这里我想给那个图像命名,同时保存是否可以将名称设置为所选图像?如果有意思请告诉我。我正在尝试,只有在可能的情况下我会发布那个。谢谢。

3 个答案:

答案 0 :(得分:1)

我就是这样做的..我正在复制并粘贴我的代码,因此还有一些额外的功能。

// image is a UIImage
// inputText is the user selected imagename
// date is a string I inserting to make pictures a unique identifier (i.e. no duplicate names)
NSData *imageData1 = UIImageJPEGRepresentation(image, 1.0);
NSString *imageFilename = [NSString stringWithFormat:@"%@-%@.jpg", inputText,date];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *path = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], imageFilename];

if([imageData1 writeToFile:path atomically:YES]){
    NSLog(@"Write to Document folder success filename = %@",path);
}

答案 1 :(得分:0)

使用以下内容:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

UIImage *photoImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSString *savedDoc = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/myImageName.png"];
BOOL status = [[NSFileManager defaultManager] fileExistsAtPath:savedDoc];

if(status){

[[NSFileManager defaultManager] removeItemAtPath:savedDoc error:nil];

}
[UIImagePNGRepresentation(photoImage) writeToFile:savedDoc atomically:YES];
[picker dismissModalViewControllerAnimated:YES];
}

保存到文档目录时,可以设置任何所需的名称。

答案 2 :(得分:0)

声明一个整数counterNo并将其初始化为0.并增加其值以动态更改名称。

UIImage *photoImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

counterNo++;

NSString *aaa = [NSString stringWithFormat:@"Documents/myImage-%d.png" , counterNo];
NSString *savedDoc = [NSHomeDirectory() stringByAppendingPathComponent:aaa];
BOOL status = [[NSFileManager defaultManager] fileExistsAtPath:savedDoc];

if(status){

    [[NSFileManager defaultManager] removeItemAtPath:savedDoc error:nil];

}
[UIImagePNGRepresentation(photoImage) writeToFile:savedDoc atomically:YES];
[picker dismissModalViewControllerAnimated:YES];