如何保存已调整大小的图像?

时间:2017-05-11 23:16:38

标签: swift uiimageview uiimage file-manager

晚上好

我正在尝试将已调整大小的图像保存在文档目录中,以避免每次调用时都必须调整大小。

分析问题就在我使用以下行时:

let jpgImageData = UIImageJPEGRepresentation (image, 1.0)

UIImageJPEGRepresentation似乎撤消了对图像所做的更改,从而以相同的比例保存图像。

任何人都知道解决这个问题的方法吗?

代码下方:

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var imgView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let myImageName = "image_10001.jpg"
        let imagePath = fileInDocumentsDirectory(filename: myImageName)
        if let image = UIImage(named:"image_10001")?.resizedImage(newSize: UIScreen.main.bounds.size){
            print("Image : \(image.size.height)")
            _ = saveImage(image: image, path: imagePath)
        }
        if let loadedImage = loadImageFromPath(path: imagePath){
            print("Screen: \(UIScreen.main.bounds.size.height)")
            print("Image Size: \(loadedImage.size.height)")
    //            let image = UIImageJPEGRepresentation(loadedImage, 0.9)
    //            let imgRes = UIImage(data: image!)?.resizedImage(newSize: UIScreen.main.bounds.size)
    ////            
    //            let load = loadedImage.resizedImage(newSize: UIScreen.main.bounds.size)
    //            
    //            print("Load: \(load.size.height)")
    //            
    //            _  = saveImage(image: load, path: imagePath)
    //            
             imgView.image =  loadedImage
    //
    //            imgView.image = UIImage(data: image!)?.resizedImage(newSize: UIScreen.main.bounds.size)
        }
        // Do any additional setup after loading the view, typically from a nib.
    }

    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
    }
    func getDocumentsURL() -> URL {
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        return documentsURL
    }
    func fileInDocumentsDirectory(filename: String) -> String {
        let fileURL = getDocumentsURL().appendingPathComponent(filename)
        return fileURL.path
    }
    func saveImage (image: UIImage, path: String ) -> Bool{
        print("Save")
        let url = URL(fileURLWithPath: path)
    //        let pngImageData = UIImagePNGRepresentation(image)
        let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
        let img = UIImage(data:jpgImageData!)
     //        
          print("SIMG: \(String(describing: img?.size.height))")
        do {
            _ = try jpgImageData?.write(to: url, options: .atomicWrite)
            print("Save Success")
        } catch let error {
            print(error)
            return false
        }
        return true
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
extension UIImage {
    /// Returns a image that fills in newSize
    func resizedImage(newSize: CGSize) -> UIImage {
        // Guard newSize is different
        guard self.size != newSize else { return self }
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
        self.draw(in: CGRect(x:0, y:0, width:newSize.width, height: newSize.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }
    /// Returns a resized image that fits in rectSize, keeping it's aspect ratio
    /// Note that the new image size is not rectSize, but within it.
    func resizedImageWithinRect(rectSize: CGSize) -> UIImage {
        let widthFactor = size.width / rectSize.width
        let heightFactor = size.height / rectSize.height
        var resizeFactor = widthFactor
        if size.height > size.width {
            resizeFactor = heightFactor
        }
        let newSize = CGSize(width:size.width/resizeFactor, height:size.height/resizeFactor)
        let resized = resizedImage(newSize: newSize)
        return resized
    }
    var jpeg: Data? {
        return UIImageJPEGRepresentation(self, 1)   // QUALITY min = 0 / max = 1
    }
    var png: Data? {
        return UIImagePNGRepresentation(self)
    }
}
extension Data {
    var uiImage: UIImage? {
        return UIImage(data: self)
    }
}

1 个答案:

答案 0 :(得分:0)

我假设您的文档目录中有一些“旧”图像,该图像是使用您的一些旧代码(未调整大小)保存的。

我认为,因为您发布的代码不会保存任何新图像,因为这一行:

if let image = UIImage(named:"image_10001")?.resizedImage(newSize: UIScreen.main.bounds.size){
    //resize code
}

我想你想在这里使用刚刚从bundle获取的相同图像名称:

if let image = UIImage(named: myImageName)?.resizedImage(newSize: UIScreen.main.bounds.size){
    //resize code
}

您可以重置模拟器内容并确认不会使用您在此处发布的代码加载任何图像。