iOS開發(fā)之Video轉(zhuǎn)GIF—Swift

前言

最近遇到需要將video轉(zhuǎn)化為gif的問題,網(wǎng)上找的在線轉(zhuǎn)換限制太多,索性就自己寫了一個(gè)工具APP。文章末尾有開源代碼和打包好的APP,如有需要請(qǐng)自行下載。

效果圖

效果圖

核心代碼

來源

class MP4ToGIF {
    private var videoUrl: URL!
    init(videoUrl: URL) {
        self.videoUrl = videoUrl
    }
    func convertAndExport(to url: URL, cappedResolution: CGFloat?, desiredFrameRate: CGFloat?, completion: ((Bool) -> ())) {
        var isSuccess: Bool = false
        defer {
            completion(isSuccess)
        }
        // Do the converties
        let asset = AVURLAsset(url: videoUrl)
        guard let reader = try? AVAssetReader(asset: asset),
              let videoTrack = asset.tracks(withMediaType: .video).first
        else {
            return
        }

        let videoSize = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
        // Restrict it to 480p (max in either dimension), it's a GIF, no need to have it in crazy 1080p (saves encoding time a lot, too)
        let aspectRatio = videoSize.width / videoSize.height

        let duration: CGFloat = CGFloat(asset.duration.seconds)
        let nominalFrameRate = CGFloat(videoTrack.nominalFrameRate)
        let nominalTotalFrames = Int(round(duration * nominalFrameRate))

        let resultingSize: CGSize = {
            if let cappedResolution = cappedResolution {
                if videoSize.width > videoSize.height {
                    let cappedWidth = round(min(cappedResolution, videoSize.width))
                    return CGSize(width: cappedWidth, height: round(cappedWidth / aspectRatio))
                } else {
                    let cappedHeight = round(min(cappedResolution, videoSize.height))
                    return CGSize(width: round(cappedHeight * aspectRatio), height: cappedHeight)
                }
            }else {
                return videoSize
            }
        }()

        // In order to convert from, say 30 FPS to 20, we'd need to remove 1/3 of the frames, this applies that math and decides which frames to remove/not process
        let framesToRemove: [Int] = {
            // Ensure the actual/nominal frame rate isn't already lower than the desired, in which case don't even worry about it
            if let desiredFrameRate = desiredFrameRate, desiredFrameRate < nominalFrameRate {
                let percentageOfFramesToRemove = 1.0 - (desiredFrameRate / nominalFrameRate)
                let totalFramesToRemove = Int(round(CGFloat(nominalTotalFrames) * percentageOfFramesToRemove))

                // We should remove a frame every `frameRemovalInterval` frames…
                // Since we can't remove e.g.: the 3.7th frame, round that up to 4, and we'd remove the 4th frame, then the 7.4th -> 7th, etc.
                let frameRemovalInterval = CGFloat(nominalTotalFrames) / CGFloat(totalFramesToRemove)
                var framesToRemove: [Int] = []

                var sum: CGFloat = 0.0

                while sum <= CGFloat(nominalTotalFrames) {
                    sum += frameRemovalInterval
                    if sum > CGFloat(nominalTotalFrames) { break }
                    let roundedFrameToRemove = Int(round(sum))
                    framesToRemove.append(roundedFrameToRemove)
                }
                return framesToRemove
            } else {
                return []
            }
        }()

        let totalFrames = nominalTotalFrames - framesToRemove.count

        let outputSettings: [String: Any] = [
            kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32ARGB,
            kCVPixelBufferWidthKey as String: resultingSize.width,
            kCVPixelBufferHeightKey as String: resultingSize.height
        ]

        let readerOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: outputSettings)

        reader.add(readerOutput)
        reader.startReading()


        let delayBetweenFrames: CGFloat = 1.0 / min(desiredFrameRate ?? nominalFrameRate, nominalFrameRate)

        print("Nominal total frames: \(nominalTotalFrames), totalFramesUsed: \(totalFrames), totalFramesToRemove: \(framesToRemove.count), nominalFrameRate: \(nominalFrameRate), delayBetweenFrames: \(delayBetweenFrames)")

        let fileProperties: [String: Any] = [
            kCGImagePropertyGIFDictionary as String: [
                kCGImagePropertyGIFLoopCount as String: 0
            ]
        ]

        let frameProperties: [String: Any] = [
            kCGImagePropertyGIFDictionary as String: [
                kCGImagePropertyGIFDelayTime: delayBetweenFrames
            ]
        ]
        guard let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeGIF, totalFrames, nil) else {
            return
        }

        CGImageDestinationSetProperties(destination, fileProperties as CFDictionary)

        let operationQueue = OperationQueue()
        operationQueue.maxConcurrentOperationCount = 1

        var framesCompleted = 0
        var currentFrameIndex = 0
        
        while currentFrameIndex < nominalTotalFrames {
            if let sample = readerOutput.copyNextSampleBuffer() {
                currentFrameIndex += 1
                if framesToRemove.contains(currentFrameIndex) {
                    continue
                }
                // Create it as an optional and manually nil it out every time it's finished otherwise weird Swift bug where memory will balloon enormously (see https://twitter.com/ChristianSelig/status/1241572433095770114)
                var cgImage: CGImage? = self.cgImageFromSampleBuffer(sample)
                
                operationQueue.addOperation {
                    framesCompleted += 1
                    if let cgImage = cgImage {
                        CGImageDestinationAddImage(destination, cgImage, frameProperties as CFDictionary)
                    }
                    cgImage = nil
                    
                    //                    let progress = CGFloat(framesCompleted) / CGFloat(totalFrames)
                    
                    // GIF progress is a little fudged so it works with downloading progress reports
                    //                    let progressToReport = Int(progress * 100.0)
                    //                    print(progressToReport)
                }
            }
        }
        operationQueue.waitUntilAllOperationsAreFinished()
        isSuccess = CGImageDestinationFinalize(destination)
    }
}
extension MP4ToGIF {
    private func cgImageFromSampleBuffer(_ buffer: CMSampleBuffer) -> CGImage? {
        guard let pixelBuffer = CMSampleBufferGetImageBuffer(buffer) else {
            return nil
        }

        CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
        
        let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer)
        let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
        
        let width = CVPixelBufferGetWidth(pixelBuffer)
        let height = CVPixelBufferGetHeight(pixelBuffer)
        
        guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) else { return nil }
        
        let image = context.makeImage()
        
        CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly)

        return image
    }
}

使用步驟

  1. 打開APP
  2. video文件拖拽到窗口中

常見問題

macos 10.15 將對(duì)您的電腦造成傷害,您應(yīng)該將它移到廢紙簍

  1. APP右鍵-顯示簡介-覆蓋惡意軟件保護(hù) 打勾
  2. 打開終端 codesign -f -s - --deep /Applications/appname.app

總結(jié)

代碼支持iOSmacOS
下載地址----->>>MP4ToGIF,如果對(duì)你有所幫助,歡迎Star。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言 最近遇到需要將gif轉(zhuǎn)化為mp4的問題,網(wǎng)上找的在線轉(zhuǎn)換限制太多,索性就自己寫了一個(gè)工具APP。文章末尾有開...
    季末微夏閱讀 697評(píng)論 0 0
  • 用到的組件 1、通過CocoaPods安裝 2、第三方類庫安裝 3、第三方服務(wù) 友盟社會(huì)化分享組件 友盟用戶反饋 ...
    SunnyLeong閱讀 15,205評(píng)論 1 180
  • 表情是什么,我認(rèn)為表情就是表現(xiàn)出來的情緒。表情可以傳達(dá)很多信息。高興了當(dāng)然就笑了,難過就哭了。兩者是相互影響密不可...
    Persistenc_6aea閱讀 129,882評(píng)論 2 7
  • 16宿命:用概率思維提高你的勝算 以前的我是風(fēng)險(xiǎn)厭惡者,不喜歡去冒險(xiǎn),但是人生放棄了冒險(xiǎn),也就放棄了無數(shù)的可能。 ...
    yichen大刀閱讀 8,162評(píng)論 0 4

友情鏈接更多精彩內(nèi)容