在iPhone应用程序中保存和加载UIImage

问题描述 投票:1回答:1

我很头疼,想知道我的应用程序有什么问题。我正在尝试保存和加载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连接,并且正在调用所有代码。我使用的方法有问题吗?

iphone objective-c load uiimage save
1个回答
1
投票

保存图像时,请替换此行:

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

使用

 [imageData writeToFile:fullpath atomically:YES];
© www.soinside.com 2019 - 2024. All rights reserved.