UIImagePickerController Save to Disk then Load to UIImageView

不打扰是莪最后的温柔 提交于 2019-12-04 16:07:26

You're writing out an NSData object, not an image. You need to read the NSData object back in and convert to UIImage.

Assuming everything else is correct, try this:

NSData *data = [[NSData alloc] initWithContentsOfFile:[self.managedObject valueForKey:@"imageLocation"]];
UIImage *image = [[UIImage alloc] initWithData:data];

Using NSDateFormatterShortStyle will cause the date to be represented as (for example) 12/11/12, which will mess up your file name. It will also use a colon in the short time representation, which is illegal.

I would recommend using a more custom date format, such as:

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"yyyyMMdd-HHmmss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

I used this code on one of my test projects and simulated the bug. Jordan was right about converting it to NSData first before changing it again to UIImage but the real problem here is on your file naming method.

I noticed that you have used the current date and time as the file name of your image. This includes characters such as ":" and "/" which is not allowed to be used on file names. http://www.portfoliofaq.com/pfaq/FAQ00352.htm

As a solution, I made the date format as what is written below:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyyMddHHmm"]; NSString *imageName = [NSString stringWithFormat:@"photo-%@.png", [dateFormatter stringFromDate:[NSDate date]]];

Hope this helps others as well. :)

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