美文网首页
Swift 屏幕截屏、图片保存到相册 功能详解

Swift 屏幕截屏、图片保存到相册 功能详解

作者: topws1 | 来源:发表于2019-07-30 21:45 被阅读0次
  • Part 1

绘制当前 Screenshot

UIGraphicsBeginImageContextWithOptions(currentView.bounds.size, false, UIScreen.main.scale)

currentView.drawHierarchy(in: currentView.bounds, afterScreenUpdates: true)

let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
  • Part 2

系统相册权限逻辑处理

Step 1
查询当前的授权状态

Step 2
处理当前的授权状态:

1.已授权 --> 直接写入相册未决定
2.请求权限 --> 如果成功直接写入相册
3.已拒绝 --> Open系统设置
private func saveImageToPhotoLibrary(image: UIImage?) {
        
        guard let img = image else {
            return
        }
        // 判断权限
        switch PHPhotoLibrary.authorizationStatus() {
        case .authorized:
            saveImage(image: img)
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { [weak self](status) in
                if status == .authorized {
                
                    self?.saveImage(image: img)
                } else {
                    print("User denied")
                }
            }
            
        case .restricted, .denied:
            if let url = URL.init(string: UIApplication.openSettingsURLString) {
            
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.openURL(url)
            }
        }
            
        }
    }
private func saveImage(image: UIImage) {
        
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        }, completionHandler: { [weak self](isSuccess, error) in
            
            DispatchQueue.main.async {
                
                if isSuccess {// 成功
                    
                    print("Success")    
                }
            }
        })
    }
  • Part 3

特殊情况处理,当用户在系统设置中把相册的权限由未授权变更为授权时,APP会自动重启,如果有需要可以在崩溃前把图片缓存到本地,启动时再做处理。

  • Part 4

附上压缩图片到指定大小的分类方法(网上找的,能用就行。。。)

import UIKit

public extension UIImage {

    /// 压缩图片的大小,并且返回压缩后的Data
    class func resetSizeOfImageData(sourceImage: UIImage, maxSize: Int) -> Data? {
        
        if let finallImageData = sourceImage.jpegData(compressionQuality: 1.0) {
            return resetSizeOfImageData(sourceData: finallImageData, maxSize: maxSize)
        }
        return nil
        
    }

    class func resetSizeOfImageData(sourceData: Data, maxSize: Int) -> Data? {
        
        //先判断当前质量是否满足要求,不满足再进行压缩
        guard let sourceImage = UIImage(data: sourceData) else {
            return nil
        }
        var finallImageData = sourceData
        let sizeOrigin      = finallImageData.count
        let sizeOriginKB    = sizeOrigin / 1024
        if sizeOriginKB <= maxSize {
            return finallImageData
        }

        //获取原图片宽高比
        let sourceImageAspectRatio = sourceImage.size.width/sourceImage.size.height
        //先调整分辨率
        var defaultSize = CGSize(width: 1024, height: 1024/sourceImageAspectRatio)
        guard let newImage = self.newSizeImage(size: defaultSize, sourceImage: sourceImage) else {
            return nil
        }
        
        guard let newImageData  = newImage.jpegData(compressionQuality: 1.0) else {
            return nil
        }
        finallImageData = newImageData
        //保存压缩系数
        var compressionQualityArr: [CGFloat] = []
        let avg = CGFloat(1.0/250)
        var value = avg
        
        var i = 250
        repeat {
            i -= 1
            value = CGFloat(i)*avg
            compressionQualityArr.append(value)
        } while i >= 1
        
        /*
         调整大小
         说明:压缩系数数组compressionQualityArr是从大到小存储。
         */
        //思路:使用二分法搜索
        
        guard let halfData = self.halfFuntion(arr: compressionQualityArr, image: newImage, sourceData: finallImageData, maxSize: maxSize) else {
            return nil
        }
        finallImageData = halfData
        
        //如果还是未能压缩到指定大小,则进行降分辨率
        while finallImageData.count == 0 {
            //每次降100分辨率
            let reduceWidth = 100.0
            let reduceHeight = 100.0/sourceImageAspectRatio
            if (defaultSize.width-CGFloat(reduceWidth)) <= 0 || (defaultSize.height-CGFloat(reduceHeight)) <= 0 {
                break
            }
            defaultSize = CGSize(width: (defaultSize.width-CGFloat(reduceWidth)), height: (defaultSize.height-CGFloat(reduceHeight)))
            
            guard let lastCompressionData = newImage.jpegData(compressionQuality: compressionQualityArr.last ?? 1) else {
                return nil
            }
            guard let lastCompressionImage = UIImage.init(data: lastCompressionData) else {
                return nil
            }
            guard let image = self.newSizeImage(size: defaultSize, sourceImage: lastCompressionImage) else {
                return nil
            }
            
            guard let sourceData = image.jpegData(compressionQuality: 1.0),
                let halfData = halfFuntion(arr: compressionQualityArr, image: image, sourceData: sourceData, maxSize: maxSize) else {
                    return nil
            }
            finallImageData = halfData
        }
        
        return finallImageData
    }
    
    // MARK: - 调整图片分辨率/尺寸(等比例缩放)
    class func newSizeImage(size: CGSize, sourceImage: UIImage) -> UIImage? {
        var newSize = CGSize(width: sourceImage.size.width, height: sourceImage.size.height)
        let tempHeight = newSize.height / size.height
        let tempWidth = newSize.width / size.width
        
        if tempWidth > 1.0 && tempWidth > tempHeight {
            newSize = CGSize(width: sourceImage.size.width / tempWidth, height: sourceImage.size.height / tempWidth)
        } else if tempHeight > 1.0 && tempWidth < tempHeight {
            newSize = CGSize(width: sourceImage.size.width / tempHeight, height: sourceImage.size.height / tempHeight)
        }
        
        UIGraphicsBeginImageContext(newSize)
        sourceImage.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    
    // MARK: - 二分法
    class func halfFuntion(arr: [CGFloat], image: UIImage, sourceData finallImageData: Data, maxSize: Int) -> Data? {
        var tempFinallImageData = finallImageData
        
        var tempData = Data.init()
        var start = 0
        var end = arr.count - 1
        var index = 0
        
        var difference = Int.max
        while start <= end {
            index = start + (end - start)/2
            
            guard let imageJpegData = image.jpegData(compressionQuality: arr[index]) else {
                return nil
            }
            tempFinallImageData = imageJpegData
            
            let sizeOrigin = tempFinallImageData.count
            let sizeOriginKB = sizeOrigin / 1024
            
            print("当前降到的质量:\(sizeOriginKB)\n\(index)----\(arr[index])")
            
            if sizeOriginKB > maxSize {
                start = index + 1
            } else if sizeOriginKB < maxSize {
                if maxSize-sizeOriginKB < difference {
                    difference = maxSize-sizeOriginKB
                    tempData = tempFinallImageData
                }
                if index<=0 {
                    break
                }
                end = index - 1
            } else {
                break
            }
        }
        return tempData
    }
}

相关文章

  • Swift 屏幕截屏、图片保存到相册 功能详解

    Part 1 绘制当前 Screenshot Part 2 系统相册权限逻辑处理 Step 1查询当前的授权状态 ...

  • ios MobileVLCKit的截屏和录屏功能

    第一、截屏功能 项目需求,点击截屏按钮,对当前直播页面截屏并且保存到相册。 MobileVLCKit这个库本身有提...

  • mac 电脑使用小技巧

    1 截图 自带截图功能 截取整个屏幕快捷键:Command+shift+3,这样就截图了整个屏幕,然后截屏的图片保...

  • 浅析APP截屏唤起功能设计

    谈到APP截屏,人们的印象中就是截屏后系统会自动将截屏的图片会保存到手机相册里面,APP自己不做处理。事实上,很多...

  • Quartz 2D (2)

    1、圆形图片裁剪 2、实现手机屏幕截屏功能(把控制器中View的内容截屏生成一张新的图片) 3、图片截屏 4、图片...

  • ios 截屏功能(高清图)

    可以通过以下代码实现截屏,然后保存到相册。

  • 对控件截屏并保存到系统相册

    前言 项目中有个需求就是对某个控件截屏,并将截屏的图片保存到系统相册。这里记录下我的实现过程。 实现过程 在具体实...

  • 如何判断UIAlertView是否显示

    最近在做一个截屏功能,把截屏的图片展示在界面上,本来是打算从相册取出直接展示在界面,因为从相册取得图片是完整的,但...

  • iOS开发-截屏

    项目需要做个截屏并保存到相册的功能,于是去网上搜了下,大部分是采用的以下方式: 不过要做的项目需要截屏的是播放视频...

  • swift - 屏幕截屏

网友评论

      本文标题:Swift 屏幕截屏、图片保存到相册 功能详解

      本文链接:https://www.haomeiwen.com/subject/gszhrctx.html