gpt4 book ai didi

ios - 保存和加载 UIImageView

转载 作者:行者123 更新时间:2023-11-29 12:14:22 27 4
gpt4 key购买 nike

我想在 UIImageView 中保存和加载图像我已经尝试了一些代码,但它不起作用。我试过的代码:

保存:

UIImage *image = ...;
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:@"image.png"];
[UIImagePNGRepresentation(image) writeToFile:cachedImagePath atomically:YES];

加载:

NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:@"image.png"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:cachedImagePath]];

但是这些代码不起作用!

最佳答案

希望你把图片保存在文档目录文件夹中这是保存图像的方法:

- (void)saveImage: (UIImage*)image
{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: @"test.png"] ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}

从文档目录获取图片:

- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: @"test.png"] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}

希望对你有帮助

关于ios - 保存和加载 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32367646/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com