保存和加载UIImage iPhone问题

时间:2012-07-24 15:39:41

标签: iphone objective-c load uiimage save

我正在努力解决我的应用程序出了什么问题。我想保存并加载UIImages,简单吧?似乎不是这样。

我有一个使用这些方法的类来保存,加载和删除带有唯一字符串的图像。我喜欢它,简单明了。这是班级:

imageSavedLoad.h:

#import <Foundation/Foundation.h>

@interface imageSaveLoad : NSObject

- (void)saveImage:(UIImage*)image forKey:(NSString*)imageName;
- (void)removeImage:(NSString*)fileName;
- (UIImage*)loadImage:(NSString*)imageName;

@end

imageSaveLoad.m:

#import "imageSaveLoad.h"


@implementation imageSaveLoad

//saving an image
- (void)saveImage:(UIImage*)image forKey:(NSString*)imageName
{
    NSData *imageData = UIImagePNGRepresentation(image);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
    NSLog(@"image saved");
}

//removing an image
- (void)removeImage:(NSString*)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", fileName]];
    [fileManager removeItemAtPath: fullPath error:NULL];
    NSLog(@"image removed");
}

//loading an image
- (UIImage*)loadImage:(NSString*)imageName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];
    return [UIImage imageWithContentsOfFile:fullPath];
}

@end

在我要保存,加载或删除图片的位置,我导入了这个类:#import "imageSaveLoad.h"

然后我创建它的一个实例并调用所需的方法(这里我保存):

imageSaveLoad *imgSL = [[imageSaveLoad alloc] init];
[imgSL saveImage:photoImgView.image forKey:@"yourPhoto"];

然后在我想要检索图像的另一个视图/类中:

imageSaveLoad *imgSL = [[imageSaveLoad alloc] init];
yourImgView.image = [imgSL loadImage:@"yourPhoto"];

yourImgView没有显示任何内容,空白。

那我哪里错了?我检查了所有IBOutlet个连接,并且正在调用所有代码。我正在使用的方法有问题吗?

任何帮助都非常感激,它让我不知所措。

1 个答案:

答案 0 :(得分:1)

保存图片时,请尝试替换此行:

 [fileManager createFileAtPath:fullPath contents:imageData attributes:nil];

使用

 [imageData writeToFile:fullpath atomically:YES];