swift存储图片到沙盒

2020-09-11  本文已影响0人  久百一

将图片保存到沙盒下,首先获取沙盒路径,追加图片名称,将图片转换成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("文件不存在")
            }
上一篇下一篇

猜你喜欢

热点阅读