Save UIImage Object as a PNG or JPEG File
In an earlier post on saving images from the camera to the Photo Album, a question was posed asking how to save the image to another directory other than the Photo Album. Let’s walk through one way to write a UIImage object, from the camera or otherwise, as a PNG or JPG file into the Documents directory.
Get UIImage Data as PNG or JPEG
UIKit includes two C functions, UIImageJPEGRepresentation and UIImagePNGRepresentationwhich will return an NSData object that represents an image in JPEG or PNG format, respectively. With this information in hand, you can then use the writeToFile method of theNSData object to write the image data to a specified path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
Important note, on lines 6 and 9, the value image must be a UIImage object.
Source Code
I’ve changed the example from the original post that wrote a UIImage from the camera to the Photo Album, to write instead to the test files shown above. You can download the source code for the application here: Write UIImage Object as a PNG or JPEG File.
Simulator Not Supported
One last note, this application will only run on an actual device as the simulator does not have camera support.
本文介绍如何将UIImage对象从相机或其他来源保存为PNG或JPEG文件,并将其写入Documents目录中。文中提供了具体的代码实现,包括设置图片路径、写入不同格式的图片以及检查文件是否成功写入的方法。
1485

被折叠的 条评论
为什么被折叠?



