UIimage保存图片和互转NSData

UIImage图片转NSData

在Iphone上有两种读取图片数据的简单方法:
1. UIImageJPEGRepresentation 取UIImage的JPEG格式的NSData 函数需要两个参数:图片的引用和压缩系数.
2. UIImagePNGRepresentation. 取UIImage的PNG格式的NSData 只需要图片引用作为参数.

通过在实际使用过程中,比较发现:

UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的图片数据量大很多.
建议优先使用UIImageJPEGRepresentation,并可根据自己的实际使用场景,设置压缩系数,进一步降低图片数据量大小.

保存图片


import UIKit func getDocumentsURL() -> NSURL { let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] return documentsURL } func fileInDocumentsDirectory(filename: String) -> String { let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename) return fileURL.path! } class ViewController: UIViewController { @IBOutlet var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Define the specific path, image name let myImageName = "image.png" let imagePath = fileInDocumentsDirectory(myImageName) if let image = imageView.image { saveImage(image, path: imagePath) } else { print("some error message") } if let loadedImage = loadImageFromPath(imagePath) { print(" Loaded Image: \(loadedImage)") } else { print("some error message 2") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //还可以改写,根据传过来的后缀名判断是存储未png还是jpg func saveImage (image: UIImage, path: String ) -> Bool{ let pngImageData = UIImagePNGRepresentation(image) //let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG let result = pngImageData!.writeToFile(path, atomically: true) return result } func loadImageFromPath(path: String) -> UIImage? { let image = UIImage(contentsOfFile: path) if image == nil { print("missing image at: \(path)") } print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder. return image } }

发表评论