如何在Swift中压缩GIF?

如何在Swift中压缩GIF?,swift,compression,animated-gif,lossy-compression,Swift,Compression,Animated Gif,Lossy Compression,我的gif生成器功能降低了分辨率并最小化了一系列照片中的帧,但我没有任何东西可以减少颜色或使其有损。我将如何在Swift 4中执行此操作 func generateGif(photos: [UIImage], filename: String) -> Bool { let documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask,

我的gif生成器功能降低了分辨率并最小化了一系列照片中的帧,但我没有任何东西可以减少颜色或使其有损。我将如何在Swift 4中执行此操作

    func generateGif(photos: [UIImage], filename: String) -> Bool {

        let documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let path = documentsDirectoryPath.appending(filename)
        let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]]
        let gifProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: 0.1]] // actual speed is 0.2
        let cfURL = URL(fileURLWithPath: path) as CFURL
        if let destination = CGImageDestinationCreateWithURL(cfURL, kUTTypeGIF, photos.count, nil) {

            CGImageDestinationSetProperties(destination, fileProperties as CFDictionary?)

            var inc:Int = 0

            for _ in 0..<15 { // actual photos.count is 31

                let photo = photos[inc]

                var width:CGFloat = photo.size.width
                var height:CGFloat = photo.size.height

                let maxWidthHeight:CGFloat = 500

                if(photo.size.width > maxWidthHeight || photo.size.height > maxWidthHeight){ // gif beyond max width or height

                    if(photo.size.width > photo.size.height){

                        width = maxWidthHeight

                        let percentChange = width / photo.size.width
                        height = photo.size.height * percentChange

                    }else{

                        height = maxWidthHeight

                        let percentChange = height / photo.size.height
                        width = photo.size.width * percentChange

                    }

                    print("w:\(width) h:\(height) inc:\(inc)")

                }

                let smallerPhoto = imageWithImage(image:photo, scaledToSize:CGSize(width:width, height:height))
                CGImageDestinationAddImage(destination, smallerPhoto.cgImage!, gifProperties as CFDictionary?)

                inc+=2 // skipping ahead incrementation for less frames
            }

// here it's saving to a photo album when it's done and reporting the filesize
            CustomPhotoAlbum.sharedInstance.savePhoto(URL: URL(fileURLWithPath: path), completion: {

                var fileSize : UInt64

                do {
                    let attr = try FileManager.default.attributesOfItem(atPath: path)
                    fileSize = attr[FileAttributeKey.size] as! UInt64
                    print("gif is \(fileSize/1000000) megabytes")
                } catch {
                    print("Error: \(error)")
                }

            })

            return CGImageDestinationFinalize(destination)
        }


        return false
    }
func-generateGif(照片:[UIImage],文件名:String)->Bool{
让documentsDirectoryPath=NSSearchPathForDirectoriesInDomains(.documentDirectory、.userDomainMask,true)[0]
让path=documentsDirectoryPath.appending(文件名)
让fileProperties=[kCGImagePropertyGIFDictionary作为字符串:[kCGImagePropertyGIFLoopCount作为字符串:0]]
让gifProperties=[kCGImagePropertyGIFDictionary作为字符串:[kCGImagePropertyGIFDelayTime作为字符串:0.1]//实际速度为0.2
让cfURL=URL(fileURLWithPath:path)作为cfURL
如果let destination=CGImageDestinationCreateWithURL(cfURL、kuttypegf、photos.count、nil){
CGImageDestinationSetProperties(目标、文件属性是否为CFDictionary?)
var inc:Int=0
对于u0..maxWidthHeight | | photo.size.height>maxWidthHeight){//gif超出最大宽度或高度
如果(photo.size.width>photo.size.height){
宽度=最大宽度高度
让百分比更改=宽度/photo.size.width
高度=照片大小高度*百分比变化
}否则{
高度=最大宽度高度
让百分比更改=高度/photo.size.height
宽度=照片大小宽度*百分比变化
}
打印(“w:\(宽度)h:\(高度)inc:\(inc)”)
}
设smallerPhoto=imageWithImage(图像:照片,缩放大小:CGSize(宽度:宽度,高度:高度))
CGImageDestinationAddImage(目的地,smallerPhoto.cgImage!,gifProperties作为CFDictionary?)
inc+=2//跳过前向增量以获得更少的帧
}
//在这里,它保存到相册,当它完成并报告文件大小
CustomPhotoAlbum.sharedInstance.savePhoto(URL:URL(fileURLWithPath:path)),完成:{
变量文件大小:UInt64
做{
让attr=try FileManager.default.attributesOfItem(atPath:path)
fileSize=attr[FileAttributeKey.size]as!UInt64
打印(“gif为\(文件大小/1000000)兆字节”)
}抓住{
打印(“错误:\(错误)”)
}
})
返回CGImageDestinationFinalize(目的地)
}
返回错误
}

任何超过500宽度或高度的文件都会返回大约11兆字节的文件。我想它可能要小得多

根据
gifsicle
上的
gifsicle查看
giflossy
。它完全可以满足你的需求,甚至更多。它是用C编写的,但你可以从中获得一些灵感,并将相关部分移植到swift。

通常,照片最好用jpg和线条艺术表示,纯色表示为gif,JPEG具有不同的压缩级别。-这里有一些信息,比如说,需要动画吗?也就是说,在你最喜欢的搜索引擎中输入“压缩swift 4 site:stackoverflow.com中的gif”,就会看到很多类似的问题,也许其中一个问题会对你有所帮助?马克,我正在循环像素当前颜色的偏移量。关于在Swift 4中压缩GIF,我真的找不到什么。事实上,如果我在Stack Overflow中搜索“compress gif swift”,当前问题的结果是三个问题中唯一相关的一个。这就是为什么我在这里问。是的,动画是必需的。我得到了大约3600个结果,你的里程数可能会有所不同