正确保存和加载图片的方式 [英] Proper way of saving and loading pictures
问题描述
我在做一个小应用程序,用户可以创建一个游戏配置文件,输入一些数据和可以用相机拍摄的图片。
我在 NSUserDefaults
的帮助下保存了大部分个人资料数据,但是一位朋友不鼓励我保存个人资料 NSUserDefault
中的图片
正确 或 缓存
文件夹。
保存到文档
文件夹:
NSString * path = [NSHomeDirectory()stringByAppendingString:@/ Documents / myImage.png];
BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path
contents:nil attributes:nil];
if(!ok)
{
NSLog(@创建文件%@时出错,路径);
}
else
{
NSFileHandle * myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[myFileHandle writeData:UIImagePNGRepresentation(yourImage)];
[myFileHandle closeFile];
}
从载入<
文件夹:
NSFileHandle * myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
UIImage * loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];
您也可以使用 UIImageJPEGRepresentation
将 UIImage
另存为 JPEG
文件。此外,如果您要将其保存在缓存
目录中,请使用:
[NSHomeDirectory()stringByAppendingString:@/ Library / Caches /]
I am making a small app where the user can create a game profile, input some data and a picture that can be taken with the camera.
I save most of that profile data with the help of NSUserDefaults
, but a friend discouraged me from saving the profile image in NSUserDefault
.
What's the proper way to save and retrieve images locally in my app?
You should save it in Documents
or Cache
folder. Here is how to do it.
Saving into Documents
folder:
NSString* path = [NSHomeDirectory() stringByAppendingString:@"/Documents/myImage.png"];
BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path
contents:nil attributes:nil];
if (!ok)
{
NSLog(@"Error creating file %@", path);
}
else
{
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[myFileHandle writeData:UIImagePNGRepresentation(yourImage)];
[myFileHandle closeFile];
}
Loading from Documents
folder:
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];
You can also use UIImageJPEGRepresentation
to save your UIImage
as a JPEG
file. What's more if you want to save it in Cache
directory, use:
[NSHomeDirectory() stringByAppendingString:@"/Library/Caches/"]
这篇关于正确保存和加载图片的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!