JPG 图像无法使用 UIImage imageNamed 加载
我在参考文献中读到,从 iOS 版本 4.+ 开始,使用 UIImage
对象的 imageNamed
方法,不需要文件扩展名。
来自 UIImage
类参考:
特殊注意事项。
在 iOS 4 及更高版本上,不需要指定文件名 文件扩展名。在 iOS 4 之前,您必须指定文件名 扩展名。
但似乎这只适用于 PNG 文件。
如果我的代码是:
[UIImage imageNamed:@"test"];
- 仅当文件为
test.png
时才加载图像 - 如果文件为
test.jpg
,则不会加载图像。
对我来说这是一个大问题,因为我需要维护动态图像加载(我在运行时不知道我要加载的图像是 png
还是 jpg
)。
请问你能帮我吗?
谢谢。
I read on the reference that from iOS version 4.+ with the method imageNamed
of UIImage
object, the file extension is not required.
From UIImage
class reference:
Special Considerations.
On iOS 4 and later, the name of the file is not required to specify
the filename extension. Prior to iOS 4, you must specify the filename
extension.
But it seems that this only work with PNG files.
If my code is:
[UIImage imageNamed:@"test"];
- The image loads only if the file is
test.png
- The image doesn't load if it's
test.jpg
.
For me it is a big problem because I need to maintain a dynamic image loading (I do not know at runtime if the image I want to load is png
or jpg
).
Please can you help me?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最新的开发人员参考指出了缺失的信息:
该库对 PNG 进行特殊处理的一个可能原因是 iOS 硬件针对 PNG 进行了优化。存储在应用程序包中的 PNG 图像由 Xcode 进行优化,更改 PNG 图像的字节顺序以匹配 iPhone 设备的图形芯片。 (请参阅此问题:PNG 是否优于 JPEG适用于 iOS 上的所有图像文件?)。
如果您知道只有 PNG 或 JPG,另一种解决方案是在 UIImage 上创建一个类别,如下所示。
The latest developer reference states the missing piece of information:
One possible reason that the library gives PNGs special treatment, is that the iOS hardware is optimized for PNGs. PNG images stored in the application bundle are optimized by Xcode, changing the byte order of the PNG images to match the graphics chip of the iPhone device. (see this question: Is PNG preferred over JPEG for all image files on iOS?).
If you know that you will only have a PNG or a JPG, an alternative solution is to create a category on UIImage as per below.
如果您的应用程序中捆绑了这些图像,您应该知道它们的扩展名。
如果您从在线源获取它们并且将它们作为 NSData,则可以在此处使用此代码来确定类型。
根据这个问题中的最佳答案。
If you have these images bundled in your app, you SHOULD know their extensions.
If you're getting them from an online source and you have them as NSData, you can use this code here to determine the type.
As per the top answer in this question.