Swift将图片保存到沙盒下

24 篇文章 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("文件不存在")
            }
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值