iOS ImageIO 的使用- CGImageDestination图像编码

这篇文章来介绍ImageIO中CGImageDestination的常见使用,CGImageDestination常见使用主要有两种:

1.添加一张或多张图片进行格式的转换并输出,并且支持写入元数据,如何查看属性请看CGImageSource的使用中的描述
2.制作动图,例如制作GIF图

基本知识

CGImageSource:解码-读取图片数据类

    //查看支持解码的type类型,日志需自行打印
    let mySourceTypes : CFArray = CGImageSourceCopyTypeIdentifiers();
    print(mySourceTypes);

CGImageDestination:编码-写入图片数据类

     //查看支持编码的type类型,日志需自行打印
     let myDestinationTypes : CFArray = CGImageDestinationCopyTypeIdentifiers();
     print(myDestinationTypes);

CGImageProperties:支持修改的属性
属性有很多类,常见的有GPS信息、拍摄设备信息、曝光度等等,这里附上Apple官方文档链接详细列表

一、图片格式转换,添加属性并保存

如果你的项目要求图像格式统一,而且是特定格式。这个时候你就需要用图像重新便来达到目的。
如果你的项目产品经理想允许用户向图像添加关键字或更改饱和度、曝光或其他值,则需要将这些信息保存在选项字典中。
CGImageDestination初始化方法有三种:
CGImageDestinationCreateWithDataConsumer():指定CGDataConsumer接收编码数据来创建
CGImageDestinationCreateWithData():指定CFData接收编码数据来创建,样例中用的便是这种创建方式
CGImageDestinationCreateWithURL():指定保存文件路径来创建,如果该文件路径已存在内容,则会被覆盖

//重编码的过程,会去掉图像资源的一些额外信息(如:TIFF、Exif等),如果需要这些原始的额外信息请通过解码获取,然后再进行编码设置
    func setImgPropertiesWithDestination(){
        let image = UIImage(named: "IMG_0851.HEIC")
        guard let newData = CFDataCreateMutable(kCFAllocatorDefault, 0) else { return }

        //1.创建CGImageDestination,type是编码后的格式("public.png"=kUTTypePNG,更支持使用UTType),count是添加image张数,optional是预留的填nil就可以
        guard let imgDestinationSource = CGImageDestinationCreateWithData(newData, "public.png" as CFString, 1, nil) else {
            print(stderr, "Fail to create imgDestination");
            return
        }
        //properties的数据,这里是通过ImageSource解码得到复制过来的,用官方宏定义替换了两个参数名kCGImagePropertyGPSDictionary、kCGImagePropertyGPSLatitudeRef
        var properties = [kCGImagePropertyGPSDictionary : ["Altitude" : "4341.225913621262",
                          "AltitudeRef" : 0,
                          "DestBearing" : "235.8580323785803",
                          "DestBearingRef" : "T",
                          "HPositioningError" : 5,
                          "ImgDirection" : "235.8580323785803",
                          "ImgDirectionRef" : "T",
                          "Latitude" : "30.423055",
                          kCGImagePropertyGPSLatitudeRef : "N" as CFString,
                          "Longitude" : "90.8759",
                          "LongitudeRef" : "E",
                          "Speed" : 0,
                          "SpeedRef" : "K"]] as CFDictionary
        //2.添加图像,设置参数
        CGImageDestinationAddImage(imgDestinationSource, (image?.cgImage)!, properties)
        //3.CGImageDestinationFinalize,在操作结束后已完成编码
        if CGImageDestinationFinalize(imgDestinationSource){//return true表示编码成功,false则编码失败
            getPropertiesWith(imageData: newData)
        }
    }

二、制作动图

以常用的GIF动图生成为例,组成动图的基本属性有2点:总的帧数和每帧的停留时间。总帧数决定了动画效果,每帧停留时间决定了动画的流畅度。
那么通过CGImageDestination生成动图,主要设置便是:
1.通过设置Properties来配置动图属性
2.通过AddImage来添加动图的组成帧数

    func createAnimatedImg(){
        let loopCount = 1
        let frameCount = 60
        let image1 = UIImage(named: "IMG_0851.HEIC")
        let image2 = UIImage(named: "IMG_0868.PNG")
        //设置动图属性,kCGImagePropertyGIFLoopCount:动图的执行次数,kCGImagePropertyGIFDelayTime:每一帧图片的执行(持续)时间
        var fileProperties = [kCGImagePropertyGIFDictionary:[kCGImagePropertyGIFLoopCount: loopCount]]
        var frameProperties = [kCGImagePropertyGIFDictionary:[kCGImagePropertyGIFDelayTime: 1.0 / Double(frameCount)]]
        //设置文件保存路径
        let filePath = String(format: "%@/%.0lf.gif", mainPath!, Date().timeIntervalSince1970)
        guard let destination =  CGImageDestinationCreateWithURL(URL(fileURLWithPath: filePath) as CFURL,kUTTypeGIF as CFString, frameCount, nil) else {
            print(stderr, "Fail to create imgDestination");
            return
        }
         
        CGImageDestinationSetProperties(destination, fileProperties as CFDictionary)
         //向Destination中添加图片,添加数量决定总帧数
        for i in 0..<frameCount {
            autoreleasepool {
                let radians = M_PI * 2.0 * Double(i) / Double(frameCount)
                let image = i%2 == 0 ? image1 : image2

                if let cropImg = cropImageWith(size: CGSize(width: 300, height: 300), origalImg: image!){
                    CGImageDestinationAddImage(destination, cropImg, frameProperties as CFDictionary)
                }
            }
        }
         //结束添加
        if CGImageDestinationFinalize(destination) {
            //进行数据验证,这里是通过解码查看元数据进行的校验,依个人喜好也可以通过加载来校验
            //getPropertiesWith(filePath: filePath)
        }
    }
    //使用的原图过大,进行了尺寸裁剪
    func cropImageWith(size : CGSize ,origalImg : UIImage) -> CGImage?{
       return origalImg.cgImage!.cropping(to: CGRect(origin: CGPoint(x: (origalImg.size.width - size.width)/2, y: (origalImg.size.height - size.height)/2), size: size));
    }
Apple官方文档:文档地址ImageIOGuide
参考的博客 iOS中的imageIO与image解码
ImageIO的使用之CGImageSource图像解码
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容