1. 程式人生 > >Swift將圖片儲存到沙盒下

Swift將圖片儲存到沙盒下

將圖片儲存到沙盒下,首先獲取沙盒路徑,追加圖片名稱,將圖片轉換成NSData型別,寫到檔案裡。
persent引數:圖片質量引數,該值越大,表示圖片越清晰,圖片檔案也就越大

//儲存圖片至沙盒
    private func saveImage(currentImage: UIImage, persent: CGFloat, imageName: String){
        if let imageData = UIImageJPEGRepresentation(currentImage, persent) as NSData? {
            let fullPath = NSHomeDirectory().appending("/Documents/"
).appending(imageName) imageData.write(toFile: fullPath, atomically: true) print("fullPath=\(fullPath)") } }

也可以通過newSize自定義圖片的大小

private func saveImage(currentImage: UIImage, newSize: CGSize, imageName: String){
        //壓縮圖片尺寸
        UIGraphicsBeginImageContext(newSize)
        currentImage.draw(in
: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) if let newImage = UIGraphicsGetImageFromCurrentImageContext() { //UIImageJPEGRepresentation此方法可將圖片壓縮,但是圖片質量基本不變,第二個引數即圖片質量引數。 if let imageData = UIImageJPEGRepresentation(newImage, 1) as NSData? { let
fullPath = NSHomeDirectory().appending("/Documents/").appending(imageName) imageData.write(toFile: fullPath, atomically: true) print("fullPath=\(fullPath)") } } }

從檔案中讀取圖片

if let savedImage = UIImage(contentsOfFile: fullPath) {
                self.imageView.image = savedImage
            } else {
                print("檔案不存在")
            }