保存一个 UIImage 并在 UIImageview 上重用它 [英] Save a UIImage and reused it on UIImageview

查看:66
本文介绍了保存一个 UIImage 并在 UIImageview 上重用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前能够拍摄照片或从相机加载并在我的应用程序的 UIImageView 中放置图像,因为我希望能够有一个按钮来保存图像,因此当我重新加载应用程序时,图像是仍然在 UIImageView 中.

I currently have the ability to take a photo or load from the camera and place an image in the UIImageView in my app be i want the ability to have a button that will save the image so when i reload the app the image is still in the UIImageView.

我的虽然是一个按钮,一旦你加载它并在

My though was a button to save the image once you have loaded it and in the

-(void)viewDidLoad

有加载已保存图像的代码,但我不知道如何处理.

have the code to load the image that was saved but i don't know how to approach this.

任何帮助都会很棒.

推荐答案

您可以使用 UIImagePNGRepresentationUIImageJPGRepresentation 将图像转换为 NSData,然后调用 NSDatawriteToFile... 方法之一将数据保存到文件中.

You can convert images to NSData using either UIImagePNGRepresentation or UIImageJPGRepresentation, then save the data to file calling one of NSData's writeToFile... methods.

然后当你重新启动你的应用程序时,你可以通过调用[UIImage imageWithData:[NSData dataWithContentsOfFile:filePath]]

Then when you restart your application, you can get the image by calling [UIImage imageWithData:[NSData dataWithContentsOfFile:filePath]]

-- 编辑 --

保存图片

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]];

我使用了 NSCachesDirectory,因为我假设您不想备份此图像(通过 iCloud 或 iTunes).如果你这样做,那么你会想要使用 NSDocumentDirectory 代替.

I used NSCachesDirectory since I'm assuming you don't want to have this image backed up (either through iCloud or iTunes). If you do then you'd want to use NSDocumentDirectory instead.

这篇关于保存一个 UIImage 并在 UIImageview 上重用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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