正确保存和加载图片的方式 [英] Proper way of saving and loading pictures

查看:122
本文介绍了正确保存和加载图片的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个小应用程序,用户可以创建一个游戏配置文件,输入一些数据和可以用相机拍摄的图片。



我在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆