我正在将.jpg文件写入我的应用文档目录,如下所示:
NSData *img = UIImageJPEGRepresentation(myUIImage, 1.0);
BOOL retValue = [img writeToFile:myFilePath atomically:YES];
稍后,我使用以下命令将该图像加载回UIImage:
UIImage *myImage = [UIImage imageWithContentsOfFile:path];
我知道它有效,因为我可以在表格单元格中绘制图像,这很好。现在,如果我尝试使用UIImageJPEGRepresentation(myImage,1.0),调试器会打印出这些行:
<Error>: Not a JPEG file: starts with 0xff 0xd9
<Error>: Application transferred too few scanlines
该函数返回nil。有没有人知道为什么会这样?加载后我没有做任何事情来操纵UIImage数据。我刚刚将UIImage提供给单元格中的图像视图。我设置了图像视图属性,使得单元格中的所有图像对齐并且大小相同,但我认为这与将UIImage转换为NSData无关。
答案 0 :(得分:21)
图像没有损坏,我能够正确显示它们。问题可能是UIImage中的一个错误,或者文档应该更清楚使用imageWithContentsOfFile:。
我可以通过更改
来消除错误消息UIImage *myImage = [UIImage imageWithContentsOfFile:path];
到
NSData *img = [NSData dataWithContentsOfFile:path];
UIImage *photo = [UIImage imageWithData:img];