iOS UIImageJPEGRepresentation错误:不是JPEG文件:以0xff 0xd9开头

vip*_*r99 11 iphone uiimageview uiimage nsdata uiimagejpegrepresentation

我正在将.jpg文件写入我的应用程序的Documents目录,如下所示:

NSData *img = UIImageJPEGRepresentation(myUIImage, 1.0);
BOOL retValue = [img writeToFile:myFilePath atomically:YES];
Run Code Online (Sandbox Code Playgroud)

之后,我使用以下命令将该图像加载回UIImage:

UIImage *myImage = [UIImage imageWithContentsOfFile:path];
Run Code Online (Sandbox Code Playgroud)

我知道它有效,因为我可以在表格单元格中绘制图像,这很好.现在,如果我尝试使用UIImageJPEGRepresentation(myImage,1.0),调试器会打印出这些行:

<Error>: Not a JPEG file: starts with 0xff 0xd9
<Error>: Application transferred too few scanlines
Run Code Online (Sandbox Code Playgroud)

函数返回nil.有没有人知道为什么会这样?加载后我没有做任何事情来操纵UIImage数据.我刚刚将UIImage提供给单元格中的图像视图.我设置了图像视图属性,使得单元格中的所有图像对齐并且大小相同,但我认为这与将UIImage转换为NSData无关.

vip*_*r99 21

图像没有损坏,我能够正确显示它们.问题可能是UIImage中的一个错误,或者文档应该更清楚使用imageWithContentsOfFile:.

我能够通过更改消除错误消息

UIImage *myImage = [UIImage imageWithContentsOfFile:path];
Run Code Online (Sandbox Code Playgroud)

NSData *img = [NSData dataWithContentsOfFile:path];
UIImage *photo = [UIImage imageWithData:img];
Run Code Online (Sandbox Code Playgroud)