0

我想拍摄 3 张图像并将其作为 IMAGE_1、IMAGE_2 和 IMAGE_3 保存在文档文件夹中。我想将图像的数量限制为三个图像,这意味着第 4 个图像将保存为新的“IMAGE_1”替换第一个图像(旧 IMAGE_1),第 5 个变为“IMAGE_2”,依此类推。下面的代码会将图像保存为 IMAGE_1、IMAGE_2、IMAGE_3、IMAGE_4、... 我应该如何限制保存的图像数量?

- (void) saveImage:(UIImage*)image 
{
    NSData *imageData =
    [NSData dataWithData:UIImageJPEGRepresentation(image, 0.9f)];
    [imageData writeToFile:[self savePath] atomically:YES];
}

- (NSString*) savePath
{
    int i=1;
    NSString *path;
    do {
    path = [NSString stringWithFormat: @"%@/Documents/IMAGE_%d.jpg", NSHomeDirectory(), i++];
} while ([[NSFileManager defaultManager] fileExistsAtPath:path]); 

    return path;
}
4

1 回答 1

1
static int i=1;  // Place it below your @implementation yourclassname

- (void) saveImage:(UIImage*)image {
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.9f)];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *path = [self savePath];

    if([fileMgr fileExistsAtPath:path])
        [fileMgr removeItemAtPath:path error:NULL];
    [imageData writeToFile:path atomically:YES];
}
- (NSString*) savePath {
    if(i==4)
        i=1;
    return [NSString stringWithFormat: @"%@/Documents/IMAGE_%d.jpg", NSHomeDirectory(), i++];
}

希望能帮助到你。

于 2013-02-10T12:19:53.900 回答