Save a UIImage and reused it on UIImageview

那年仲夏 提交于 2019-12-24 08:38:37

问题


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.

Any help would be fantastic.


回答1:


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

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

-- EDIT --

Save image

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

Load image

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

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.



来源:https://stackoverflow.com/questions/19228241/save-a-uiimage-and-reused-it-on-uiimageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!