2013-02-10 51 views
0

我想拍攝3張圖像並將其作爲IMAGE_1,IMAGE_2和IMAGE_3保存在文檔文件夾中。我想將圖像數量限制爲只有三張圖像,這意味着第四張圖像將被保存爲替換第一張圖像(舊的IMAGE_1)的新「IMAGE_1」,第五張圖像將被保存爲「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; 
} 

回答

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++]; 
} 

希望它能幫助。

+0

我試了你的答案,但是所有新圖像都保存爲IMAGE_3 :( – askingtoomuch 2013-02-10 13:20:58

+0

現在試試上面修改過的代碼,我修改了一下,這是我的一個小錯誤 – 2013-02-10 13:23:06

+0

它應該像現在的魅力:) – 2013-02-10 13:31:00

相關問題