iOS开发笔记-103:Swift5 - 获取视频第一帧图片

avplay: AVPlayerItem
let itemPath: AVURLAsset = avplay.asset as! AVURLAsset
//获取视频第一帧图片
        let gen = AVAssetImageGenerator.init(asset: itemPath)
        gen.appliesPreferredTrackTransform = true
        let time = CMTimeMakeWithSeconds(0.0, preferredTimescale: 1)
        var actualTime : CMTime = CMTimeMakeWithSeconds(0, preferredTimescale: 0)
        do {
            let imageCg = try gen.copyCGImage(at: time, actualTime: &actualTime)
    //            let imgdata = image.jpegData(compressionQuality: scale);
            let image = UIImage.init(cgImage: imageCg)
            var data: Data!
            if image.pngData() == nil {
                data = image.jpegData(compressionQuality: 1)
            } else {
                data = image.pngData()
            }
            let how = data.count / 1024
            //        JJLog("how =\(how)kb\n")
            //比例
            let scale:CGFloat = (how > 200) ? (CGFloat(200/how)) : 1.0
            //压缩图片,图片上传不能大于200kb
            data = image.jpegData(compressionQuality: scale);
            let imageString = data.base64EncodedString()

            uploadVideoImgData(vImgDataStr: imageString)
        } catch  {
            print("错误")
        }

你可能感兴趣的:(iOS开发笔记-103:Swift5 - 获取视频第一帧图片)